• Asynchronous (non-blocking) lazy loading of external javascript

Here’s a simple solution to the issue of having external javascript components make your page look like it loads slow. Of course, if you need the javascript “as soon as possible” (meaning that you wish the javascript to run at the same time as your page is rendered), then you should not do this. Instead just go for an asynchronous load.

Background: At cSupport we try optimize the load as much as possible. Recently we had a request if the script could appear completely non-loading (the browser doesn’t display the load animation).

Method: What we do is basically make the javascript first load upon the window load event (thus first when the website is fully loaded). To get it to work in Webkit I also had to add one millisecond timeout to make the script run after the load event. This works in all major, modern browsers (tested in IE, Firefox, Chrome/Safari)!

View GIST: https://gist.github.com/danschultzer/5277605

Code:
javascript "Non-blocking lazy loading of javascript" (function(d){ var scrs=d.getElementsByTagName("script"); var scr=scrs[scrs.length-1]; var w=window; function n(){ var e=d.createElement("script"); e.async=true; e.src=("https:"==d.location.protocol?"https://":"http://")+"example.org/path/to/javascript.js"; scr.parentNode.insertBefore(e,scr); } function s(){ f=w.setTimeout(n,1); // Webkit fix } if (w.attachEvent) w.attachEvent('onload', s); else w.addEventListener('load', s, false); })(document);

Here’s the info attached for more details.

This is a method to do non-blocking lazy loading of javascript.

Description

What this does is that if you have an external script on your website which has a slow connection, this slow connection will not affect the apparent load. While a non-blocking asynchronous setup will not block the load of the webpage, it will still show up in the progress bar. What we do to prevent this, is that we first add the asynchronous load after the window has sent the load event. In Webkit I had to run it right after the load event, so there is an added 1 ms.

Features

  • Insert external script the same place as this script
  • Adds an asynchronous (non-blocking) external load
  • Loads the script AFTER the page itself has loaded, thus not “slowing” the load experience
  • Minified function/element names

Tested

Tested with IE 9, Chrome 26, Safari 6, Firefox 19. Should work with all modern browsers.

Idea

http://friendlybit.com/js/lazy-loading-asyncronous-javascript

The Author

Dan Schultzer is an active experienced entrepreneur, starting the Being Proactive groups, Dream Conception organization, among other things. You can find him at twitter

Like this post? More from Dan Schultzer

Comments? We would love to hear from you, write us at @dreamconception.