how do I prevent slow loading external js files from blocking the loading process of the whole website (because the browser processes 2 requests only at a time)?
Let's say I want to include the sharethis button but the server is encountering heavy load and needs to long to serve my request, how can I force the rest to load anyway. Or should I add the external scripts after the site has loaded already?
I'm using RoR with jQuery.
Best,
Ole
Personally I would load the extra items after the ones that you need.
For example add the code to bottom of the page so that jQuery has already loaded and then load them from jQuery like below
$(document).ready(function(){
$.getScript("urlofscript");
});
Details of getScript() here
You should dinamycally load the external JavaScripts by using $(document).ready() function of jQuery.
You'll have to create the <script> elements and append them to your document.
place your javascripts the end of the page, just before < /body>
Definitely place this blocking script at the end of your page, before </body>.
Or if you want to lazily load it / don't actually need the script for the page to load, then the document.write() option is good.
I also recommend reading the web page optimization rules from this page: http://code.google.com/speed/page-speed/docs/rtt.html.
Or read either of Steve Souder's books: "High Performance Websites" and "Even Faster Websites"
Just put the <script> elements at the end of the document (just before the </body> tag).
Related
Where is the best place to put Jquery code (or separate Jquery file)? Will pages load faster if I put it in the footer?
Put Scripts at the Bottom
The problem caused by scripts is that
they block parallel downloads. The
HTTP/1.1 specification suggests that
browsers download no more than two
components in parallel per hostname.
If you serve your images from multiple
hostnames, you can get more than two
downloads to occur in parallel. While
a script is downloading, however, the
browser won't start any other
downloads, even on different
hostnames. In some situations it's not
easy to move scripts to the bottom.
If, for example, the script uses
document.write to insert part of the
page's content, it can't be moved
lower in the page. There might also be
scoping issues. In many cases, there
are ways to workaround these
situations.
An alternative suggestion that often
comes up is to use deferred scripts.
The DEFER attribute indicates that the
script does not contain
document.write, and is a clue to
browsers that they can continue
rendering. Unfortunately, Firefox
doesn't support the DEFER attribute.
In Internet Explorer, the script may
be deferred, but not as much as
desired. If a script can be deferred,
it can also be moved to the bottom of
the page. That will make your web
pages load faster.
EDIT: Firefox does support the DEFER attribute since version 3.6.
Sources:
http://www.w3schools.com/tags/att_script_defer.asp or better:
http://caniuse.com/#feat=script-defer
All scripts should be loaded last
In just about every case, it's best to place all your script references at the end of the page, just before </body>.
If you are unable to do so due to templating issues and whatnot, decorate your script tags with the defer attribute so that the browser knows to download your scripts after the HTML has been downloaded:
<script src="my.js" type="text/javascript" defer="defer"></script>
Edge cases
There are some edge cases, however, where you may experience page flickering or other artifacts during page load which can usually be solved by simply placing your jQuery script references in the <head> tag without the defer attribute. These cases include jQuery UI and other addons such as jCarousel or Treeview which modify the DOM as part of their functionality.
Further caveats
There are some libraries that must be loaded before the DOM or CSS, such as polyfills. Modernizr is one such library that must be placed in the head tag.
Only load jQuery itself in the head, via CDN of course.
Why? In some scenarios you might include a partial template (e.g. ajax login form snippet) with embedded jQuery dependent code; if jQuery is loaded at page bottom, you get a "$ is not defined" error, nice.
There are ways to workaround this of course (such as not embedding any JS and appending to a load-at-bottom js bundle), but why lose the freedom of lazily loaded js, of being able to place jQuery dependent code anywhere you please? Javascript engine doesn't care where the code lives in the DOM so long as dependencies (like jQuery being loaded) are satisfied.
For your common/shared js files, yes, place them before </body>, but for the exceptions, where it really just makes sense application maintenance-wise to stick a jQuery dependent snippet or file reference right there at that point in the html, do so.
There is no performance hit loading jquery in the head; what browser on the planet does not already have jQuery CDN file in cache?
Much ado about nothing, stick jQuery in the head and let your js freedom reign.
Nimbuz provides a very good explanation of the issue involved, but I think the final answer depends on your page: what's more important for the user to have sooner - scripts or images?
There are some pages that don't make sense without the images, but only have minor, non-essential scripting. In that case it makes sense to put scripts at the bottom, so the user can see the images sooner and start making sense of the page. Other pages rely on scripting to work. In that case it's better to have a working page without images than a non-working page with images, so it makes sense to put scripts at the top.
Another thing to consider is that scripts are typically smaller than images. Of course, this is a generalisation and you have to see whether it applies to your page. If it does then that, to me, is an argument for putting them first as a rule of thumb (ie. unless there's a good reason to do otherwise), because they won't delay images as much as images would delay the scripts. Finally, it's just much easier to have script at the top, because you don't have to worry about whether they're loaded yet when you need to use them.
In summary, I tend to put scripts at the top by default and only consider whether it's worthwhile moving them to the bottom after the page is complete. It's an optimisation - and I don't want to do it prematurely.
Most jquery code executes on document ready, which doesn't happen until the end of the page anyway. Furthermore, page rendering can be delayed by javascript parsing/execution, so it's best practice to put all javascript at the bottom of the page.
Standard practice is to put all of your scripts at the bottom of the page, but I use ASP.NET MVC with a number of jQuery plugins, and I find that it all works better if I put my jQuery scripts in the <head> section of the master page.
In my case, there are artifacts that occur when the page is loaded, if the scripts are at the bottom of the page. I'm using the jQuery TreeView plugin, and if the scripts are not loaded at the beginning, the tree will render without the necessary CSS classes imposed on it by the plugin. So you get this funny-looking mess when the page first loads, followed by the proper rendering of the TreeView. Very bad looking. Putting the jQuery plugins in the <head> section of the master page eliminates this problem.
Although almost all web sites still place Jquery and other javascript on header :D , even check stackoverflow.com .
I also suggest you to put on before end tag of body. You can check loading time after placing on either places. Script tag will pause your webpage to load further.
and after placing javascript on footer, you may get unusual looks of your webpage until it loads javascript, so place css on your header section.
For me jQuery is a little bit special. Maybe an exception to the norm. There are so many other scripts that rely on it, so its quite important that it loads early so the other scripts that come later will work as intended. As someone else pointed out even this page loads jQuery in the head section.
Just before </body> is the best place according to Yahoo Developer Network's Best Practices for Speeding Up Your Web Site this link, it makes sense.
The best thing to do is to test by yourself.
I am currently working on a website that includes several very large Javascript files. These files are causing the load time of the page to become very slow.
The output of the javascript files are initially hidden to the user behind several jquery tabs. I was wondering if it is possible to load the files only when the user clicks on those specific tabs so that the initial load time of the website wouldn't be slow?
Javascript files can be loaded dynamically upon demand when you need them.
This will be an asynchronous operation so you will start the loading process and then some time later the script will be loaded and available to you.
In jQuery, you can use $.getScript().
Example:
$.getScript("test.js", function() {
// script is loaded now
// code that uses this script can go here
});
FYI, there are other techniques for improving the load time of your site. For example, you can put all non-essential scripts (those not involved in the initial display of your page) at the very end of the <body>, right before the </body> tag. This will allow your page to display without waiting for those scripts to load.
Scripts can also be marked async and defer so that other aspects of page loading will NOT wait for them to load.
Other useful references on this topic:
Script Tag - async & defer
Deferred scripts and DOM
load and execute order of scripts
improving website performance by dynamically loading javascript?
Yes you can do this. See
http://community.sitepoint.com/t/dynamically-loading-js-script/40207/15
You will probably have to do some string concatenation in the filename when writing out the src attribute so its loads the different file you require
I have a website whose navigation is all done via ajax (with jquery); each page is dynamically loaded into an element on the page. While I have a universal stylesheet and JS scripts, each page also has a page-specfic stylesheet and JS script. What is the most effect/efficient way to load these page-specfic scripts and stylesheets? On page load, most of the page-specfic scripts/stylesheets will not be needed. A page's scripts/stylesheet will only be needed when a user loads in (via ajax) a particular page. Should I load every single script and stylesheet at page load?
Another option would be to simply append appropriate <link> and <script> elements to the head when a page is dynamically loaded; however, would they be called? Also, would I need to remove the <link> and <script> elements when a different page is called (via ajax)? For the scripts, I could use jQuery's .getScript() function. What is the best approach to this in terms of efficiency and cross-browser support?
Thank you!
Js and CSS are one time load and are browser cached (depends on your server conf as well)
So if you have an ajax, with just 1 JS inclusion. You could
Insert this JS at the footer of your home page (lazy loading; pre-emptive thinking .. faster 2nd pages)
Bring the include JS tag along with ajax response. (nothing complex here. browser makes fresh JS call)
Combine all your JS/CSS into one combined JS, push it to home page head tag (eyeing performance and caching)
once document ready, do similar to #1 using getScript() as you suggested
Well one way I know of that this can be done is with RequireJS,
but the downside is that all the JS you have need to be defined as AMDs.
Don't know if you know anything about RequireJS, but its quite a neat library,
you can imagine it as a dependency injector and loads files in async way.
If you are interested you can check their docs:
Intro
CSS
Before I have commented what you could do with the CSS.
This is how you can work with js:
var script = document.createElement('script');
script.src = "path to your src";
// load event
script.onload = function () {
//some staff
};
document.head.appendChild(script);
Also, for you, I'll recommend reading this gist.
Another good information.
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 about to embark on a new web project and I plan to put some JavaScripts in the <head> and also some before </body>, using the following scheme:
Scripts that are essential for the UX of the page: in the <head>. As I've picked up perusing the web - scripts in the <head> is loaded before the page loads, so it would make sense to put scripts that are essential to the user experience there.
Scripts that are non-essential to the design and UX (Google Analytics scripts etc.): before the </body>.
Is this a sensible approach?
Another approach would be to put all the scripts in the <head> and add defer attributes to the non-essential scripts. However, I read that older versions of Firefox don't pick up the defer attribute.
I think a lot of developers run JavaScript just before the </body> so that it is run after all the elements have been rendered.
However, if you organise your code correctly, the position on the page doesn't matter.
For example, when using jQuery, you can ensure the code isn't run until the page and its elements are fully rendered by doing the following:
$(document).ready(function(){
//Code here
});
Then the script reference can be put in the head tag.
Script tags should be referenced just before </body>. This prevents render blocking while the scripts load and is much better for site perception speed.
No obtrusive JavaScript should be used when using this technique.
JavaScript code should be placed at the end of the document so that it doesn't delay the parallel loading of page elements. This does then require that the JavaScript code is written in a specific way, but it does improve the speed of page loads.
Also, ideally you could host references like this under a different (sub)domain. References to jQuery should be pointed to Google's CDN too.
See Best Practices for Speeding Up Your Web Site for more information.
One of the reasons you'd want to put scripts before the </body> is if they manipulate the DOM without user interaction, so you'll need the DOM to be loaded in order to be manipulated. Another way to do that is to add an event listener and run the scripts when the page has loaded, but this will require additional code, which might get complicated if you have a lot of scripts, especially ones you haven't written yourself. Putting them at the end of the page also will speed up page load, though in the case of DOM manipulating scripts you might get some not-so-pretty results from that.
I'd say that's perfectly sensible. As you said, as long as you don't move essential scripts (e.g. jQuery, Modernizr, etc., etc.) out from the <head>, you shouldn't have problems.
Moving non-essential scripts to the bottom of the page should help with the perceived loading speed (that and minimizing / concatenating scripts).
It all depends on what you mean by "essential for UX". I agree with having Modernizr appear early for example, but not everything needs to load straight away. If you're trying to avoid a flash of unstyled text (FOUT), that's a good reason. Similarly, if you have scripts that affect how the page looks before the user does anything, you should load those early.
Don't forget though, speed is part of UX. There's no advantage in having some jQuery interaction ready to run when the user can't see the content it applies to yet. The difference between loading the scripts at the start of the end is a matter of seconds. If you let the page load first, the user will be using those seconds to take the page in, allowing you to load scripts unobtrusively.
Your page will load faster if you move scripts to the bottom of the page, and that makes a difference to your pagerank these days.
Also, some versions of Internet Explorer will throw errors if you try to run a script before the element it refers to has loaded.
Like Ed says, your scripts should be stored in a separate file, and in as few files as possible.
Put the JavaScript code in a separate file and place a link to it in the head part of the HTML.