I need to implement javascript and css resources for the framework I'm working on, but I have a BIG concern.
If you take a look at current websites like Facebook, Google, Youtube and other top-tier sites, their source code show their usage of javascript in various places in the code. The first question coming into my mind is... isn't supposed for javascript source files to be allocated at the beginning of the document? You can/should be able to place javascript commands enclosed in script blocks, but... source files, too??
The books I've been reading suggests (as best practices, I guess) all source files should be allocated in the head section, while displacing all code blocks to the end of the page, right before closing the body section (when possible).
Same applies for CSS. I've seen pages where, in the middle of the page, you find a source file inclusion, while the normal declaration is to include all css files in the beginning (as it's more efficient than in-place inclusion because they load in parallel that way).
In my thoughts, and if I'm to follow the books I've been reading, source files (both javascript and css) go always on top, script blocks (when possible) go to the bottom part of the document and CSS inclusions are to be avoided in-place (except for when you want to use the scope attribute or it's a style declaration inside an html tag, which should also be avoided when possible).
Is that right?
Best practice dictates thus:
CSS files should go into the <head> of the document, as near to the top as possible. I usually place mine after any <meta> tags.
JavaScript files should go as close to the end of the <body> as possible, usually directly before the </body> tag.
This is because JavaScript files load serially and are blocking, so if JavaScript files are included in the <head> of a page, all files must load in their entirety before the main body of the document can load, which often creates the perception of a delay.
Really, there is little difference between JavaScript files and JavaScript script block. They both use the <script> element, it's just that externally referenced files have an src attribute. From the point of view of the parser, they are the same.
From a validity point of view, <script> elements may be placed anywhere in the <head> or <body> of a page, and there are times when <script> files should go in the <head>, such as when using something like typekit, as this will ensure font files are loaded in time for the fonts to be displayed as soon as the page has loaded, preventing a FOUF (flash of unstyled font)
Related
Should the RequireJS script tag be located in the <head> or bottom of an HTML page?
<script data-main="resources/js/main" src="require.js"></script>
I have seen reputable sources place the RequireJS script tag in either position, but no reputable source seems to explicitly say where the ideal location is.
Arguments for placing the tag in the head would be that RequireJS could already begin loading and executing dependent scripts asynchronously while the page continues loading (though this gain may be minuscule).
Arguments for placing the tag at the bottom of the page would be that checks for the DOM being ready wouldn't be needed within modules (though not including this check may cause problems if the module is used in a third-party system that loads the script in the <head> tag).
General best practice is to always place your script at the bottom.
You may have seen people including it in the HEAD as it is not doing a big difference.
I'd recommend in the bottom, because as you'll want to build your scripts before production, you'll end up loading all your script in the head otherwise.
Note that if you're running a "single page application", then it really doesn't matter as chances are your body will be empty - or almost empty.
Put it at the bottom of the page, it's better for performance and if you're planning to manipulate the page (as expected) then you want it to load the page first anyway.
Best practice, with few exceptions, is always:
Load styles (css)
Load structure (html)
Load scripts (functionality)
I'm working on a project with a lot of templates and about 1MB of js on page load, and putting requireJS at the top of the page has it's perks. Require can start scheduling and parsing js while the rest of the html downloads. Also, we have noticed that, this allows us to 'require' css in the page before all of the html comes down.
I did find one caveat today, where script tags might execute twice if require is loaded in the page at the head/ before the script tag. I'm trying to create an example to debug.
I mean : I know the JS is cached only if it come from a .js file. Also, 90% of my functions must be rendered when the page (html) is loaded (rendered), so it is better put JS before closing the body tag. (this prevent also to use document .ready(); and the loading of the page itself will be more faster).
So, which is the advantage on putting JS in the <head></head>? Expect the "order" of the code, which I don't mind so much to be honest...
Placing a <script src> tag inside the <head> section makes sense – semantically. It does block the browser from rendering anything until the script is loaded but assures that an object (e.g. jQuery) is available in the rest of your code (in the body for example).
A common practice is to load a light weight script loading library (HeadJs, LABjs, etc) inside the head section, then load the heavy stuff lazily and/or on-demand.
Having said that, HTML5 introduced the async attribute for script tags and re-introduced the defer attribute (docs). So you now have a very good and valid reason for putting <script src> tags inside head sections because:
it makes sense
the script still loads after the page has finished loading
The <script> tag causes two problems:
Everything below the script won't render until the script is loaded.
All components below the script don't start downloading until the script is done.
Putting it into the <head> only really makes sense if you need to execute some JavaScript before anything gets rendered.
So placing it as low as possible in the page would result in a better user experience.
It's slightly more semantic to put it in the header, but it doesn't generally have any advantages. Sometimes it is necessary - for example, loading fonts using JavaScript (using stuff like Google Webfonts) has to be done in the header, or the page will render with the wrong font and then change, which won't look good to the user.
The important thing about the elements in the <head> section are that they are loaded, before the <body> starts to load.
This is a very efficient feature, which are used a lot (IMO).
Loading of libraries, scripts, that have to run before the DOM has loaded have to done in <head> section.
I will give you a scenario
Imagine, You needed to calculate the 30% size of the screen's total size and assign it to the element inside.
It would be foolish and wait for the element to load big, then run the script to load resize it again.
I am building a Rails app, and it seems that common practice is to have javascript_include_tags listed on top of a page.
Would it makes browers load javascript before loading the document, and thus makes visible elements take longer to load?
Thank you.
As far as I've read on the web, best practice loads javascript files at the bottom of the body tag. This lets almost everything load before executing the javascript, which generally prevents problems accessing items that may not exist if you loaded the script at the top.
A Yahoo post about web page performance suggests including them at the bottom of the page (Source) because they can block parallel downloads of other dependencies if they are at the top.
Looks like some answers were right, but none sums it all up:
How to prevent javascript loading from loading other elements? Simple, put it right before the closing </body> tag. Which usually means a few characters before the end of your HTML page.
Put all your javascript in external .js files. Why? So that the browsers can cache those files even when the HTML page changes.
Aggregate and minify all your javascript files into one. Why? Because the fewer HTTP requests your clients make, the faster the page loads.
Also, you don't have to care about $(document).ready() or window.onload, since all your HTML elements will be loaded before the javascript files (that is, if you put the JS files right before the closing </body> tag).
It's a good idea to use external JS file and to minify it's content.
http://www.quirksmode.org/js/placejs.html
Bottom of the page is also an option like John Fisher said.
If using i.e. jQuery you in any case use $() or $(document).ready(function() which makes sure the page DOM is loaded before you try to use your JS functions.
Rather than embedding the behavior in its markup, try to segregate the script
by moving it to a script block in the section of the page, outside the scope of the
document body, as follows:
<script type="text/javascript">
window.onload = function() {
document.getElementById('testButton').onclick = function() {
document.getElementById('xyz').style.color = 'red';
};
};
</script>
For performance reasons, script blocks can also be placed at the bottom
of the document body, though modern browsers make the performance
difference rather moot. The important concept is to avoid embedding behavioral
elements within the structural elements.
NOTE: I am in no way advocating multiple heads within a page
I'm using Apache Tiles and I have a few tiles that include their own heads. The result of the Tiles renders into an HTML page with multiple heads.
My questions:
How is the resulting page handled in IE and Chrome? [It renders and appears successful]
WITH APACHE TILES What is the best practice for dealing with/avoiding multiple heads [for CSS/Javascript] without having to demand all pages use the same JS and CSS files.
For Example with Question Two:
Lets say you have the following pages: home, profile, and gallery listing. Gallery listing has fancy JQuery+YUI+... and more styles. For most users, they would only be interested in the home and profile pages, so why slow them down with loading the JS and CSS files associated with Gallery.
This is what is generated
<html>
<head>
<title>The Template's Title</title>
</head>
<body>
<head> <script src="javascriptfile.js"/></head> Tile One Content
<head> <script src="javascriptfile2.js"/></head> Title Two Content
</body>
</html>
The generated contents is running the script in javascriptfile.js, and javascriptfile2. What I'm asking in the first question: is the extra heads ignored, and the contents considers? are they combined into the html/head level? Is it possible to include CSS files in the second or later head? Will this create an error with a stricter DTD?
Well, in modern Chrome, it's at least possible to know what happens. Chrome uses the HTML5 parser algorithm which describes exactly how invalid mark-up is processed. The gory details are at http://dev.w3.org/html5/spec/tree-construction.html#parsing-main-inbody
What happens in your example is that the first <head> in <body> is discarded. Then the <script src="javascriptfile.js"/> tag is processed, which is a start tag, not a self-closing tag, so everything that follows, including everything that looks like a tag, becomes a text child of the script element. Nothing is displayed and no script is run. If <script src="javascriptfile.js"/> is replaced by <script src="javascriptfile.js"></script>, and ditto for <script src="javascriptfile2.js"/>, the head start and end tags are silent discarded, and the script elements are not moved. "Tile One Content Title Two Content" is displayed and the scripts are run. The DTD makes no difference at all.
IE is somewhat trickier to know, as before IE10, it doesn't use the HTML5 parser algorithm and therefore it's exact behaviour is a mystery. However, a cursory experiment appears to show that it has the same behaviour as described above.
Although some legacy browsers move elements that can only appear in the head - such as <link> - into the head, other browsers do not, and no such behaviour can be relied upon.
All in all, best steer well clear of such constructs.
I don't know about practices for Apache Tiles.
What is the purpose of doing something so egregiously invalid? And why you're asking this seems very unclear.
Not only should you only have ONE <head></head> section on a page, under no circumstances is the <head></head> to be nested anywhere inside the <body></body> section.
This practice makes absolutely no sense whatsoever....
(Side-note: Certain browsers ignore or move invalid tags when the DOM is constructed which will defeat your entire purpose of doing this.)
EDIT (based on comments):
For anyone interested in including <script> tags within the <body>, you can read more about the specific details in my answer here...
Will linking javascript files in the body rather than in the header cause a problem?
You don't really need extra heads to include additional css/js. You can 'inline' the whole <style type="text/css">...</style> part and it will render fine. Will it validate? No. But will run fine.
How is the resulting page handled in IE and Chrome? [It renders and appears successful]
I don't know and I really don't want to know.
What is the best practice for dealing with multiple heads [for CSS/Javascript] without having to demand all pages use the same JS and CSS.
Don't do it :-)
Is there a reason you can't just include the JS files in the body / head without the extra tags?
Or add the css / js files in the 'normal' head section of the document (where it should be).
Well atleast you want the CSS files to be loaded as soon as the page starts loading. JS files can (sometimes) be loaded at the end of the HTML.
For example if the JS files need to have a completely loaded DOM (for e.g. accessing DOM elements).
Note
Sorry this isn't really an answer to your question, however what you are doing just looks way bad. :) And is almost certainly not needed / there will be a better solution for it.
As JavaScript in blocks HTML rendering, and it's good practice to keep JavaScript at bottom, just before closing body tag , is it not the case with CSS also?
I know we can't keep external CSS outside .
CSS does not block in the same way JavaScript does
To quote Yahoo's Developer Network Blog
With stylesheets, progressive rendering is blocked until all stylesheets have been downloaded. That’s why it’s best to move stylesheets to the document HEAD, so they get downloaded first and rendering isn’t blocked. With scripts, progressive rendering is blocked for all content below the script. Moving scripts as low in the page as possible means there's more content above the script that is rendered sooner.
In addition, when CSS is added to the head, it is parsed first, and results in the HTML being styled even as it is downloaded. This avoids the Flash Of Unstyled Content that happens if you place style tags at the bottom of a large page of HTML.
Not only does CSS not block the way Javascript does, but also some browsers will do strange things if you put CSS anywhere but the <head>, like ignore it, or apply it incompletely. HTML5 actually prohibits <style> from appearing outside <head> (except with the "scoped" feature, which AFAIK nobody implements yet).
CSS stylesheets are loaded using the <link> element, this element is only valid when it is in the head of the document. As for CSS blocking HTML rendering, this isn't the case because the CSS is applied once the browser is loaded just like the other <link> elements. JS blocks HTML because the browser assumes the JS wants to take control and actually do something before loading the DOM fully, basically JS is executed and then left alone.
Think about it, if CSS was loaded the same as JS, no element would be styled because it would be referring to elements not yet loaded, therefore it is applied afterwards and doesn't block loading.
No, css is apply to DOM element right after the browser read the css.
In case of javascript you can keep the script at read, since you make it run after all html loads, like:
window.onload = function (){
//here we start
}
JS
Since JS can change your web page (modify the DOM) browsers wait for all external JS to be downloaded (parallely), interpreted and executed before continuing with the rest of the HTML that comes after <script src="..." >
Therefore it's a good practice to put all external JS at the bottom of the <body>. This way your HTML gets parsed and rendered and your user has a feeling that something is happening...
CSS
CSS on the other hand cannot change the DOM, cannot make any "heavy" changes on the page and that is why the browser doesn't block download, parsing of the rest of the HTML, and progressive rendering as is case with the JS. It seems that it does block the rendering, but it is still better to put it at the top and avoid the long FOUC . It doesn't block download, though
Now, seems that with the rise of mobile devices putting your CSS to your HEAD and JS at the bottom is not enough... You will want to put the ATF (above the fold) CSS inline and the rest of your huge minimized CSS together with your JS - at the bottom / defered and async
Take a look at this: http://addyosmani.com/blog/detecting-critical-above-the-fold-css-with-paul-kinlan-video/
Why would it be a good practice to keep Javascript at the bottom?
I'd say that it's best practice to put CSS as well as Javascript in separate files and include them in your HTML document using the <head> section.