Skip to content

Instantly share code, notes, and snippets.

@davidhund
Created January 20, 2015 09:43
Show Gist options
  • Save davidhund/bfbe0ef49a54b5f9c2f6 to your computer and use it in GitHub Desktop.
Save davidhund/bfbe0ef49a54b5f9c2f6 to your computer and use it in GitHub Desktop.
Script Loading Pattern
/*
* Taken straight from: http://www.lognormal.com/blog/2012/12/12/the-script-loader-pattern/
*/
(function(url){
// Section 1
var dom,doc,where,iframe = document.createElement('iframe');
iframe.src = "javascript:false";
iframe.title = ""; iframe.role="presentation"; // a11y
(iframe.frameElement || iframe).style.cssText = "width: 0; height: 0; border: 0";
where = document.getElementsByTagName('script');
where = where[where.length - 1];
where.parentNode.insertBefore(iframe, where);
// Section 2
try {
doc = iframe.contentWindow.document;
} catch(e) {
dom = document.domain;
iframe.src="javascript:var d=document.open();d.domain='"+dom+"';void(0);";
doc = iframe.contentWindow.document;
}
doc.open()._l = function() {
var js = this.createElement("script");
if(dom) this.domain = dom;
js.id = "js-iframe-async";
js.src = url;
this.body.appendChild(js);
};
doc.write('<body onload="document._l();">');
doc.close();
})('http://some.site.com/script.js');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment