Load 3rd party scripts in parallel with the rest of your content without blocking onload.
Prepare a small snippet like Nicolas Gallagher's code to launch 3rd party scripts.
(function (win, doc, script) {
var js,
fjs = doc.getElementsByTagName(script)[0],
add = function (url, id) {
if (!doc.getElementById(id)) {
js = doc.createElement(script);
js.src = url;
js.async = true;
id && (js.id = id);
fjs.parentNode.insertBefore(js, fjs);
}
};
// Google Analytics
win._gaq = [["_setAccount", "UA-XXXXX-X"],["_trackPageview"]];
add(('https:' == location.protocol ? '//ssl' : '//www') + '.google-analytics.com/ga.js', 'ga');
// Google+ button
add('https://apis.google.com/js/plusone.js');
// Facebook SDK
add("//connect.facebook.net/en_US/all.js#xfbml=1", "facebook-jssdk");
// Twitter SDK
add("//platform.twitter.com/widgets.js", "twitter-wjs");
// Pocket SDK
add("https://widgets.getpocket.com/v1/j/btn.js?v=1");
}(window, document, 'script'));
Wrap above code with parent.window
and save it as snippet.js.
var win = parent ? parent.window : window;
(function (window, document) {
// above codes here
}(win, win.document));
Fetch snippet.js with frame-in-frame method that is described in this post by Stoyan Stefanov.
(function (url) {
setTimeout(function () {
var iframe = document.createElement('iframe');
(iframe.frameElement || iframe).style.cssText = 'display:none';
iframe.src = 'javascript:false';
var where = document.getElementsByTagName('script')[0];
where.parentNode.insertBefore(iframe, where);
var doc = iframe.contentWindow.document;
doc.open().write('<body onload="' +
'var js = document.createElement(\'script\');' +
'js.src = \'' + url + '\';' +
'document.body.appendChild(js);">');
doc.close();
}, 0);
}('snippet.js'));
That's it!
- GitHub Pages
- Basic pages:
- Practical pages:
- May 8, 2010 Lazy Loading Asyncronous Javascript – Friendly Bit
- Oct 25, 2011 LightningJS: safe, fast, and asynchronous third-party Javascript | Something People Want
- Nov 23, 2011 Aaron Peters Why loading third party scripts async is not good enough
- Jun 28, 2012 Non-onload-blocking async JS / Stoyan's phpied.com
- Jun 28, 2012 Non-onload-blocking Async JS with require.js
- Dec 8th 2012 Under the Hood: The JavaScript SDK – Truly Asynchronous Loading
- Dec 9th 2012 Performance Calendar » The non-blocking script loader pattern
- olark/lightningjs
- meebo/embed-code
- pablomoretti/jcors-loader