I know that standard JS code, which will be immediately executed should be placed before body's closing tag.
But what about libraries? Where should I place e.g. reference to jQuery?
Put Scripts at the Bottom so that they load after all DOM is loaded so less time to load page content.
Put your jQuery code in DOM Ready
Read Best Practices for Speeding Up Your Web Site
Related
Much of jQuery depends on $(document).ready ... why does bootstrap 2.0 include the javascript library calls at the very end?
Is there a way to get $(document).ready to work keeping the js lib calls at the very end?
Update: A common example (and the source of my frustration!) is $("#id").click(), which does not seem to work if you do not place it inside the .ready function...
jQuery only "depends" on $(document).ready() to support scripts that are evaluated while the document is still being loaded (e.g. scripts residing in the document's <head> or halfway through its <body>).
Placing scripts at the end ensures the rest of the document is loaded by the time the scripts are evaluated, so $(document).ready() is not necessary in that case.
I expect it loads it at the end of the file to improve the performance - see Yahoo best practices.
Can you put your own JS script tag after the jQuery load? If you put it after the jQuery load it should work and it should also allow your page to display whilst your code is loaded.
I'm confused about where to place JavaScript functions:
When should they be put within the head
When inline within the body
And, when after the closing html tag?
thanks
The rules are fast and loose on this, There is no right or wrong way only better and less-better. (well after the </html> is wrong)
Generally speaking, javascript in the head of the document might block rendering of the page until the file is loaded in some browsers *cough*IE*cough*. This is due to a limit of simultaneous connections. So some people put them before the closing html tag. You can use a library to asynchronously load the javascript to avoid this blocking.
If you're using a library, or checking for the DOM to be loaded before executing code there's really no issue of where it's placed. However if you're not doing that it's probably better to put it at the end.
Javascript can always be safely placed in the head to make the functionality available to the entire page. Note that this can block loading of the rest of the document, so if you are loading very large or external Javascript, you may wish to load them inline near the end of the body.
Javascript placed inline will become available when executed. This allows you to conditionally load JS when page elements are loaded.
Javascript should always be placed in the <head> or <body>, never after </html>.
I agree, never seen (nor could I recommend) after html. Also, as noted, blocking is the concern. What I often go with is one script reference in the head to yepnope (an async js loader and testing tid bit (now included with modernizr)), and a tiny block of inline js at the end of the body tag that loads a bootstrap js file.
In that file, I use another yepnope request to load other needed assets asynchronously, and kick off initialization methods.
I've also taken to putting my Google Analytics code in a final yepnope block, so that it's the last thing to load, even after the js app boots.
It's a known fact that jQueryMobile loads pages with ajax and is not including in DOM the header content in every pages.
I need to load a custom js file in some pages, how can I achieve this? Until now I have placed the .js files in the body, but there are some problems with the code there too so it's not a good workaround. Until I can find a solution I will use the rel="external" workaround, but I really need to find an answer to my question.
You could try including the custom script within the data-role="page" div in pages where you want to use those javascript.
From JQM docs:
Another approach for page-specific scripting would be to include
scripts at the end of the body element. If you include your custom
scripting this way, be aware that these scripts will execute when that
page is loaded via Ajax or regular HTTP, so if these scripts are the
same on every page, you'll likely run into problems. If you're
including scripts this way, we'd recommend enclosing your page content
in a data-role="page" element, and placing scripts that are referenced
on every page outside of that element. Scripts that are unique to that
page can be placed in that element, to ensure that they execute when
the page is fetched via Ajax.
You could use some javascript to dynamically add the js file to the DOM.
This is demoed here: http://www.javascriptkit.com/javatutors/loadjavascriptcss.shtml
I am inspecting some interesting behaviors of browser, I don't know it's in standard or not. If I put everythin inside <head></head>, the browser will only begin to render the page after all the resouces in head is retrieved.
So I am thinking that put as little as possible things into head is one of the important website optimization techniques, is it right? My question is:
If I put script/css in body or other parts of the html, how can I know that script has been loaded successfully so that I will not be calling a undefined function?
To answer shortly: You should really put the script tags at the very end of the <body> element. Style tags should be put in <head>, otherwise the document will have to be re-rendered every time a new stylesheet is loaded, so you really want them all to be loaded before the document starts rendering.
As for using javascript code that is not loaded yet. Of course you shouldn't bind any events or anything too early, and shouldn't have inline javascript in the page ideally. The solution can be to just use the window onload event to do your initialization, if you really must have inline code in the page.
My friend read an article which mentioned that moving all JavaScript files to the end of the closing body tag (</body>), will improve the performance of a web page.
I have moved all JS files to the end except the JQuery and the JS files which are attaching event to an element on page, like below;
$(document).ready(function(){
//submit data
$("#create_video").click(function(){ //... });
});
but he's saying to move the jQuery library file to the end of body tag.
I don't think it is possible, because I am attaching many events to page elements on load using jQuery selectors, and to use jQuery selectors it is must to load jQuery library first.
Is it possible to move JQuery library file to the end of page right before closing body tag (</body>) ??
Thanks
It's standard practice to move all your js includes to the bottom of your page. This is because when a browser loads script, it does not spawn a new thread to do so, so basically the browser will wait until it has loaded the script before it proceeds to the next line.
What this means for your users is that they will see a blank screen. Much better to have them see the full(ish) page as then it doesn't look like it has stalled.
The $(document).ready function says not to run until the DOM has finished being instantiated - so moving it to after body is okay so long as the JQuery library is loaded first. Unconventional and some assumptions may not be correct anymore but okay.
Just take in account that the jQuery JavaScript file must be loaded before any call to the $(...) function.
Use a "Dom Ready Queue" to collect functions to be executed once jQuery is loaded and the DOM is ready.
Example:
<html>
<head>
<script type="text/javascript">
var domReadyQueue = [];
</script>
</head>
<body>
...
<div class="foo"></div>
<script type="text/javascript">
domReadyQueue.push(function($){
$('.foo').doSomething();
})
</script>
...
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript">
jQuery(function(){
while (domReadyQueue.length) {
domReadyQueue.shift()(jQuery);
}
});
</script>
</body>
</html>
The reason that article asked you to move scripts to the bottom, is to allow other artifacts to get downloaded first. (css & images, which will speed up apparent rendering times)
This is because HTTP 1.1 recommends only downloading 2 items per hostname. And you would definitely want your css file to be one of the first files downloaded, rather than javascript which could make the site appear to render slower (just by the fact that the browser hasn't got the css file yet and isn't sure what it should do with the html)
But if you used google to host your jQuery then that would download in parallel and negates any reason for moving it to the bottom of your pages.
Alternatively, you could set up a second hostname to host static content (such as css/scripts/images).
But google have already done the hard work for you, so it makes sense to use it if it suits. :-)
Q - Why do I often see JavaScript
written/included before the closing
body element in an (x)HTML document?
A - DOM elements can not be accessed
by JavaScript until the browser has
loaded the HTML elements into the DOM.
By placing JavaScript at the end of an
(x)HTML document (before the closing
body element), you will ensure that
the script is called as soon as the
DOM is constructed/loaded and ready
for manipulation. An advantage of this
approach is that JavaScript code is
executed right after the DOM is
constructed and possibly before the
onload event would fire.
JavaScript beginners get tripped up by
this constantly by placing code that
manipulates the DOM in the header
element of an (x)HTML document. This
causes an error because the DOM has
not yet been constructed and thus is
not yet accessible to JavaScript that
traverses/manipulates the DOM.
From JavaScript Execution & Onload Techniques in Web Browsers
Use unobtrusive javascript (adding event listeners to elements instead of onclik ="..." etc).
Put all your .js files at the bottom of the body tag, with the main library (jQuery in this case) placed first, and everything will be fine. You can use a bundler like bundle fu
You will see a big performance boost of loading your page.