Last active
November 26, 2017 09:10
-
-
Save englishextra/10712436aa14df45d7031fd739bf9dfc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*! | |
* load CSS with requestAnimationFrame | |
* stackoverflow.com/questions/28394097/async-loading-css-stylesheet-using-requestanimationframe | |
* gist.github.com/englishextra/10712436aa14df45d7031fd739bf9dfc | |
*/ | |
function loadCSSwithRaf(h, c, m, b) { | |
function l() { | |
var t = window.document.createElement("link"), | |
a = b || window.document.getElementsByTagName("script")[0], | |
s = window.document.styleSheets; | |
t.rel = "stylesheet"; | |
t.href = h; | |
t.media = "only x"; | |
if (c) { | |
t.onload = c; | |
}; | |
a.parentNode.insertBefore(t, a); | |
t.onloadcssdefined = function (cb) { | |
var f; | |
for (var i = 0; i < s.length; i++) { | |
if (s[i].href && s[i].href === t.href) { | |
f = !0; | |
} | |
}; | |
if (f) { | |
cb(); | |
} else { | |
setTimeout(function () { | |
t.onloadcssdefined(cb); | |
}); | |
} | |
}; | |
t.onloadcssdefined(function () { | |
t.media = m || "all"; | |
}); | |
return t; | |
} | |
"function" === typeof requestAnimationFrame ? requestAnimationFrame(l) : "function" === typeof mozRequestAnimationFrame ? mozRequestAnimationFrame(l) : "function" === typeof webkitRequestAnimationFrame ? webkitRequestAnimationFrame(l) : "function" === typeof msRequestAnimationFrame ? msRequestAnimationFrame(l) : "function" === typeof window.addEventListener ? window.addEventListener("load", l) : window.onload = l; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This solution doesn't work. The browser starts painting the CSS when the media attribute is changed from "only x" to the intended query.
requestAnimationFrame
should be used withint.onloadcssdefined
.