Structure with Javascript code? CSS, Divs and then Scripts? - javascript

I have noticed that the place of scripts is not irrelevant, if script refers to some div below, it may not work, not sure about rules perhaps my messy code assign some other value later. So I am asking general guide-lines to design the structure in Javascript code. What is the order for example to the parts such as CSS, Divs and Scripts?
My personal bias is that good code should be easy to read from the bottom to the top. So, for example, a browser could have browse() script at the bottom to start browsing and the rest junkies that it uses to to top in logical order, so after browse() its above script should be something that the browse() uses. Field values should be defined at the top, I think things like CSS and divs -- rude analogy I know. But if user's browser is slow, the script may not execute at all and the code seems to be non-working. Dilemma between practicability and readability.
Please, define terms, such as top-to-bottom coding and bottom-to-top coding, and show the structure.

In head, put CSS, then scripts in order of usage and in body Divs.
Example if you use jQuery and have a .js file that uses jQuery code, it's adviced to import the jQuery files before your .js
Personally I try to avoid putting scripts in the body and rarely face such issues as scripts not finding divs below.

Usually I try and place scripts that manipulate DOM on the bottom of the page, it solves the problem of not finding the DOM elements before a page is fully loaded.
However, libraries (such as jQuery) should go in <head>.

You can consider the entirety of the page, JavaScript, CSS, and HTML, as a combination "top to bottom" generic program, where later code can reference earlier code. Because when the page loads, it simply starts "executing" or interpreting "code" as it sees it. Most of the time, that "code" is simply definitions (like JS vars or functions), and placement of elements (like DIVs).
However, if you have JS that actually runs during load, that is code, that is outside of a function definition, then it's going to only "see" things that exist before the code is executed. So, in that sense, the whole thing is simply one long program, with the HTML as a meta-language building a DOM as the HTML is interpreted by the browser.
Obviously there are techniques to run code at certain points, like page load, etc., and that's where the libraries like JQuery come in to to expose those event points and make them easy to use.
But fundamentally, it's a top down script, like pretty much anything else.

I try not to have excessive script block ins my code at all. I call all external scripts in the head or just before body close in the case of some api inclusion (addthis for example). All inline scripting goes in a single block at the just before the close of the body tag as well.

RequireJS - Outsourcing Script Loading
I have found RequireJS particularly useful for JavaScript application development. In my case I'm dealing with tens of JavaScript files (modules) but I'm sure it will come in handy in other cases as well.
The library handles a lot of boring stuff for you. All you need to do is to set up some files (main.js, build options), state module dependencies and you are good to go. It includes a build system so you can easily get a debug or production build (minified) done.
On Application Structure
I like to code "top-down". The idea is that higher levels of an application should be really loosely defined. You shouldn't see actual algorithms used for solving some specific problems there. The highest level should be just about wiring parts of an app together. The lower levels solve more specific problems till you get to concrete implementations.
This is a fairly standard, layered approach to application development. You probably won't need something like this for casual scripting. It's still a good idea to apply in practice as it helps you to compose your scripts better. You can use the idea on closure level even to make the code easier to read.
On Functions
It might help to read "function" as "to" (Logo concept :) ). I think a well-written function reads like a recipe (to "drawLine" you must do this and that using these parameters...).
I know this might not be exactly pertinent to the question but I thought it might be a fun idea to mention. Perhaps it will help you to see functions differently and help you to structure your JavaScript code that way.
On Elements Not Ready
Considering elements not ready and script loading... you might be better off defining your code at a "document ready" handler. This is fairly standard thing to do.
If you use RequireJS or a similar library you probably don't have to worry about this. They handle this particular issue for you.

The style sheets go first and scripts go later. The reason for this is scripts are "blocking", meaning that while the browser is downloading JavaScript, it will not download anything else - not style sheets, nor images.
Browsers will only download so many resources at one time, and will block all other loads until this number of resources free up. IE8 actually will download quite a few at a time, as many as 18 or more. Firefox and Safari will download 6 at a time, but IE6&7 will only download one script or two non-scripts at one time. The thing to keep in mind is these resources are not free, and scripts are different.
A good rule of thumb is to put your style sheets in the head and your JavaScript at the very bottom of the body. Of course JS libraries give you some sort of "on DOM ready" to attach to. You can use this, and most devs do, but there are side effects:
IE occasionally barfs on the DOM-loaded hack. Rare, but it's happened to me.
Your page will be frozen until your scripts load if they are in the head. If you have too many scripts, that can make your page look slow and non-responsive.
If your JavaScript is all at the end of the page, you'll never need to worry if stuff is loaded or a DOM node is available. And the page will be rendered and styled while your JavaScript is loading and calculating.
Finally, keep your resources to an absolute minimum. If you have more than two scripts and two style sheets, your page is not as fast as it could be. Images too - make full use of image sprites. There should only be a handful of images unless you are dealing with thumbnails or something like that.

K-I-S-S is my dogma. When my code does not work, it starts usually to work when I kill non-intrinsic code.
Some good things are covered in replies such as mwilcox and prodigitalson.
No unnecessary pictures and no excessive script blocks. Actually, some people seems to have working-JS-code of over 500 000 lines, example with Gmail.
I have no idea how they do it but it hints to be critical about the replies here! Further replies could cover how to design massive JS code like of the size 100 000 lines, for the time being.
Exceptions
libraries and analytics scripts are an exeption and go to the beginning (if needed at all). Due to this kind of messy things, you may see why the term structure become confusing. But to craft some sort of structure, it would look something like:
CSS
Divs
scripts at the end

Related

Is it worth collecting jQuery-related scripts to run them at the end of the document?

I want to place jQuery just before the closing </body>-Tag like it's recommended. But because I'm using a Content Management System, inline scripts that require jQuery will be executed before the closing body tag.
My question now is: Is it worth to collect jQuery-based scripts in an array and run them at the end of the document when jQuery is loaded (EXAMPLE) OR just load jQuery in the head section?
You could adopt the approach described here
the idea is to create a q global variable soon in the header and use a temporary window.$ function to collect all the code/functions/plugin jQuery dependent.
window.q=[];
window.$=function(f){
q.push(f);
};
and after you load jQuery you will pass all the functions to the real $.ready function.
$.each(q,function(index,f){
$(f)
});
in this way you will be able to safely include your jquery code before the jQuery lib inclusion
If this could be better than loading jQuery in the head it may depends on how much code you have to push into q temporary function.
jQuery placed into <head> section would require a single blocking script. But if you have much code to inject everywhere inside the document you may have a lot of huge blocking scripts that stop the rendering process.
On the contrary loading a lot of scripts after dom ready event it could easily make your page faster to load so this approach it's better and the benefits can be more evident.
So there's no a definitive answer valid for all code and all pages: even if this kind of technique anyway is generally good and preferable (because you have the benefit of a as-later-as-possible script execution), you should ever make some test with both the approaches and look at loading and rendering time. The article at the beginning has some consideration on the performance but also explains why stackoverflow didn't use it.
Just load jQuery in the head, it will be cached after the first load and won't slow down anything after that.
Everything else sounds like it would be over the top and I am not sure that the gain in performance will be that significant to justify the extra work.
Also sometime if your page load slowly with the javascript at the bottom it can take longer to come and load which means the visual without javascript might be visible and not provide such a good experience to the user.

Running code just before </body> instead of waiting for DOM ready/DOMcontentloaded event

Is there any drawback to putting code (which will interact with the DOM, adding event listeners and so on) just before the closing </body> tag?
<!-- all the HTML comes before this -->
(function() {
do_stuff_with_the_DOM();
})();
</body>
It seems to work in my own tests, but I never see this method used in tutorials, code examples, or other people's projects. Is there a reason not to do it? Are there edge cases that only seem to pop up when you begin using this in production and see many page views across a variety of browsers?
My project doesn't use jQuery or any other toolkit, and I'm aware of the alternatives that mimic jQuery's $(document).ready() functionality. Do I really need to use one of those? (It should go without saying, but I'm looking to run the code before window.load.)
Note that the code I want to run (do_stuff_with_the_DOM() in the example above) would be defined in an external script file, if that makes a difference.
You should put your JavaScript code in the place that makes the most sense for what it needs to do. In most cases, you need your js to attach events to DOM objects, which is hard to imagine if those DOM objects don't exist when the js is running. So putting it at the bottom of the html is a sensible, simple, and common approach. Is it the best? That's arguable.
Another approach is to attach your JavaScript to the various events that different browsers fire when the DOM is fully loaded. There is nothing wrong with this, although detractors don't like that it's often done in a way that requires an additional blocking HTTP request in the head element.
Event delegation offers a third approach that lets you attach events to parent elements (such as body) very early, and when appropriate child events exist the events will fire as if they had been attached to those elements all along. It's a very cool approach with theoretically the best early-loading performance of any of the above, but has pitfalls in that not all events bubble all the way to the top, like you might expect, and that it often tempts you to separate your JavaScript into multiple chunks, which can violate separation of content and behavior.
In General
Putting code just before </body> should always be the aim.
Its highly recommended, as the download of scripts (if requesting external JavaScript files) blocks parallel downloading (i.e. whilst a script is downloading, nothing else - be it another script or an image for example - can be downloaded at the same time).
The only time you should have an issue with this, is in something like a poor CMS system where you need to have jQuery in-place in the <head> in order for some of its scripts to work.
Using inline JavaScript
Adding inline JavaScript (or inline CSS code) to a page is generally considered bad practice as, for one, its a merging of concerns (i.e. you no longer have true separation between HTML/CSS/JS).
I cannot think of a negative performance issue if you did have all your code inlined - indeed Google use this as a practice (they load all their JavaScript in a bit comment (so that it isn't parsed) and then eval() elements of this blob of "text" as and when they need to.
I would note however, that its unlikely nowadays that you'll have many pages that don't at some point have a requirement on at least one external JavaScript file (be that JQuery, Mootools, Underscore of Backbone). In which case, as you will always have at least one external file (unless you're going to Google route), then you might as well put both external references AND inline code together... at the bottom. Creating consistency.
References
Yahoo Developer Network best practices
Google Page Speed - Defer the loading of JavaScript

Only running javascript required for current page, best methods?

So I know it's best to have one javascript file for an entire site to limit http requests. So obviously only some javascript is required for some pages. What is the best way of only running the javascript required for the current page?
EG.
if(page=='home'){
//run javascript require for the home page
}
Maybe this isn't an issue and if targeting elements are not found on the page javascript will just fail gracefully? I would just like to know the best practice for this javascript structure.
Encapsulate your logic in functions. Then just call the function(s) you need in each page, either via "onload" or an embedded function call in the page:
<script type="text/javascript">
yourFunctionForThisPage();
</script>
Edit: Just to clarify: my answer is assuming the (implied) constraint of a single .js file. As others have pointed out, although you save on HTTP requests, this is not necessarily a good idea: the browser still has to parse all the code in the file for each page, whether used or not. To be honest it's pretty unusual to have a global site-wide js resource with everything in it. It's probably a much better idea to logically split out your js into various files, i.e libraries. These libraries could be page-based - i.e specific code for a particular page, or algorithm/task-based that you can include in whatever pages need them.
Is this feasible?
While it is best to have just a single Javascript file per page to lower the number of requests yet it may not be feasible. Especially the way that you'd like to do it.
If you're asking how to join various scripts of various pages into a single script and then running just those parts that are related to a particular page then this is something you shouldn't do. What good is it for you to have one huge file with lots of scripts (also think of maintainability) compared to a few short integrated scripts? If you keep the number of scripts low (ie. below 10) you shouldn't be to worried.
The big downside is also that browser will load the complete script file which means it will take it more time to parse them as well as consume a lot more resources to use it. I'd strongly suggest against this technique of yours even though it may look interesting...
Other possibilities
The thing is that the number of Javascript files per page is low. Depending on the server side technology you're using there are tools that can combine multiple script files into one so every page will just request a single script file which will combine all those scripts that this particular page will use. There is a bit overhead on the server to accomplish this task, but there will be just one script request.
What do you gain?
every page only has scripts that it needs
individual script files are smaller hence easier to maintain
script size per request is small
browser parsing and resource consumption is kept low
Know what you will need on the page and use a script loader like labjs.
Also, remember that your specific case might be different from what others have found, so you might want to do some tests, to verify if, for example, having 5 little files, is better (or worse) than 1 big file.
The only way to be sure is to test different options yourself and come up with a fitting solution.

javascript basic question

While declaring Javascript in a html document. We have 3 ways to do that
script section goes in the head tag
script section goes in the body tag
javascript is references from an external file
Which one of these is faster and efficient with respect to performance is considered?
Thanks
Put javascripts/references to linked scripts at bottom of page if possible. As suggested here: http://developer.yahoo.com/performance/rules.html
1 and 2 are about tag location. 3 could apply to both 1 and 2.
In addition, you can have javascript in event handler attributes, like so:
<button onclick="alert(1)">pressme</button>
to top it off, you can also have javascript as url, in for example links:
click me
Just sticking to your examples: first of all, it is usually a good idea to use external script files that you load with a src component in tags. This allows the browser to cache the script, which allows the page to load faster after the initial page load. this is especially true if you use things like jQuery and load them from a public Conent delivery network (like the google ajax api see: http://code.google.com/apis/ajaxlibs/documentation/)
As for the location (head or body): in the olden days, people used to say, put your scripts in the head to ensure they are loaded once the body is loaded and all the interactive elements can be used by the user. But the problem with that is that the loading of those scripts will block loading of the visual part of the page, the body. Basically, the users are looking at a blank page, wondering whuy their page is taking so long to render.
So nowadays, the popular wisdom is to put all scripts as far down in the body as you can, and make sure that you write your javascript in a way that it can handle partially loaded scripts. The YSlow guide is a great resource to learn about these things. see:
http://developer.yahoo.com/yslow/help/
It really depends on what type of JavaScript you are writing. If you writing code that needs to be executed in the body (for ex: document.write()) you will have to write that in the body tag. If that is not the case and if you are writing javascript functions then should go in the head tag or in a different file. You would use a different file if you are going to use the same functions across many pages.
w.r.t performance, it again depends on what you are doing. If you have just one page that uses javascript, it would be faster to keep it in the header. This way you would reduce a round trip to get the javascript file.
If you have multiple pages that use the same functions, then it will be faster if the functions are in a different file because they will be downloaded once and used multiple times.
I'd say it depends on the circumstances.
An external file is a good idea if you have a large script that is used across a site and you want to take advantage of client-side caching mechanisms.
If a script is only used on one page then keeping it in the head/body might make sense. Clearly the earlier the script comes in the page the sooner the JavaScript will be executed, but you may be constrained by waiting for the DOM to be available to the script anyway, in which case it won't make any difference if it's in the head or the body.
You could put the script immediately after any HTML that defines the DOM that it needs access to. This would probably be the quickest way of getting a script to execute in the page, but don't go for this over an externally loaded (and cached) file if it is large or used in many places.
If you're super concerned about performance, I would say loading the js in the html would be fastest. Items in the load before the rest of the page, so from a user's perspective, they may think the download takes longer with js since the page won't start to render until after the is loaded, but the amount of data should be the same. External js file is likely the slowest since it will require a separate http request.
The short answer is...well...it depends.
If by
faster and efficient with respect to performance is considered
you mean "loads faster", then inline script in the head will get your code into the browser faster the first time it's loaded. An external file can be cached, so if you're including the same script in multiple pages, once you overcome the overhead of loading it the first time, then you have it resident in memory.
I prefer to have my Javascript and HTML all in the same file just because I don't like having a lot of different tabs open. But then again it is a lot neater to use your Javascript, HTML, and CSS all in different files.
So far, the more complicated/long the code is, I'd use a different file, but if the code is simple, I'd just use the same file for everything.

Is there any good reason for javascript to be inline

I've been building a site. At some stage I noticed that IE display was a little broken and Chrome had all but rendered nothing but the body tag (empty), and FF all looked good.
After throwing my keyboard around the room and bashing my head against my mouse, I discovered the problem. I had left (don't ask how or why, must have been some lightning speed cut and paste error) an HTML comment unclosed in an inline script block.
<script type="text/javascript">
<!--
...
</script>
I'm guessing (not tested) the problem would have either not come up, or manifested itself in a far more noticeable way if the script was external. So anyways, I got to thinking, is there ever a time when you have a really good reason to write inline script??
No. Write Unobtrusive Javascript.
If you want your Javascript to run as early as possible, it might make sense to include inline Javascript, since it will run before any other HTTP requests have necessarily completed.
And in some cases, you're including Javascript from a 3rd party provider and you don't really have a choice. Certain ad systems, as well as Google Analytics, spring to mind.
If the script must be dynamically generated (say by a PHP or ASP.NET MVC page) would be one reason to have it inline :-)
Depends on how much JS do you plan to write. If you're writing many support routines (lots of validation checks, text processing, animation and effects) then it makes sense to have the code in a separate file. This allows code reuse and removes a lot of junk from your HTML page.
On the other hand, there is no need to put 10 lines of code, or a single function (a refresh JS comes to mind) in a separate file. It will also load slightly faster, since the browser does not need to make an additional HTTP request to download the separate JS file.
Most XSS vulnerabilities can only be exploited using inline javascript.
It's not necessarily enough of a reason, but the pages will load faster. To this end, sometimes, even when you write the script in another file, you want it to show up as inline on the client side.
I sometimes place javascript inline in pages that get partially reloaded (to bind some events to newly added form-fields for example) and / or pages that use some unique javascript that I will not use on any other page.
Having many external scripts can ultimately slow down the page as the browser must call each file separately. Combining the JavaScript into one file or into the page itself can sometimes alleviate this problem.
On the other hand, I believe the browser may cache a script file once it's been called for the first time so if you have a lot of the same code across your site, external is the way to go.
I work a good deal in something called Flex, which combines XML and ActionScript to create the final bytecode. It is ALWAYS best practice to separate the two as much as possible. That way, you can very clearly and easily separate the View (the HTML or MXML in my case) from the Controller (the script)
It also means that you do not have to worry about looking through five files for one line of code -- all of your code is in one place.
File caching is the reason to have external js and css files. Even if you only have one HTML page, this page is likely to be updated often and so will be downloaded by the browser as often. If the js (and css) are in the HTML page, that too will be downloaded often. Keeping them separate will keep the HTML file smaller and will download faster. The js and css files will have been cached so will not be continually downloaded. That is assuming these files are not updated very often.

Categories

Resources