views:

190

answers:

5

Hi,

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

+2  A: 

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.

FWH
+1  A: 

place your javascripts the end of the page, just before < /body>

skrat
A: 

Just put the <script> elements at the end of the document (just before the </body> tag).

David Dorward
+3  A: 

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

AutomatedTester
One thing to note: If the external script uses document.write to add it's stuff to the page, you won't be able to use this method - the document.write overwrites the entire page! I had this issue with google maps until I discovered that in their case you can add async=2 to the querystring.
Olly Hodgson
+1  A: 

definitely place this blocking script at the end of your page, before .

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

strife25
good link, thanks!
ole_berlin
glad i could help, I definitely recommend installing the firebug add-ons called Pagespeed or YSlow, basically the same thing and mae by the same guy (Souders). Pagespeed was an internal Google tool to measure performance until recently.The tools basically look at the current page, see how they measure up against the performance rules you see on the page i linked to, and tell you what you can do to make your page faster.
strife25