Skip to content

Instantly share code, notes, and snippets.

@danschultzer
Last active December 15, 2015 14:49
Show Gist options
  • Save danschultzer/5277605 to your computer and use it in GitHub Desktop.
Save danschultzer/5277605 to your computer and use it in GitHub Desktop.
This is a method to do non-blocking lazy loading of javascript, preventing your page to look "loading slow" due to external loads.
(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);
/*
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/
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment