Skip to content

Instantly share code, notes, and snippets.

@mjlescano
Last active August 29, 2015 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mjlescano/43c9befe3a0e46a59c80 to your computer and use it in GitHub Desktop.
Save mjlescano/43c9befe3a0e46a59c80 to your computer and use it in GitHub Desktop.
Global asyncCss() function to load async stylesheets, can accept callback as second argument that will be executed when all the stylesheets had finished loading. (IE6 compatible in theory.)
;(function(w,d){
var rAF = w.requestAnimationFrame
|| w.mozRequestAnimationFrame
|| w.webkitRequestAnimationFrame
|| w.msRequestAnimationFrame
|| function(f){ f() }
var callbacks = []
var pending = 0
var hasOnload = 'onload' in d.createElement('link')
var head = d.getElementsByTagName('head')[0]
function p(){
pending--
if( pending <= 0 ) {
for( var i = 0, length = callbacks.length; i < length; i++ ) {
rAF(callbacks.shift())
}
}
}
asyncCss = function(href, callback){
pending++
if( callback ) callbacks.push(callback)
var link = d.createElement('link')
link.rel = 'stylesheet'
link.href = href
link.onload = link.onerror = p
rAF(function(){
head.parentNode.insertBefore(link, head)
if( !hasOnload ) p()
})
}
})(window,document);
;(function(a,c){function f(){d--;if(0>=d)for(var g=0,a=e.length;g<a;g++)k(e.shift())}var k=a.requestAnimationFrame||a.mozRequestAnimationFrame||a.webkitRequestAnimationFrame||a.msRequestAnimationFrame||function(a){a()},e=[],d=0,m="onload"in c.createElement("link"),l=c.getElementsByTagName("head")[0];asyncCss=function(a,h){d++;h&&e.push(h);var b=c.createElement("link");b.rel="stylesheet";b.href=a;b.onload=b.onerror=f;k(function(){l.parentNode.insertBefore(b,l);m||f()})}})(window,document);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment