Skip to content

Instantly share code, notes, and snippets.

@englishextra
Last active November 26, 2017 09:10
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 englishextra/10712436aa14df45d7031fd739bf9dfc to your computer and use it in GitHub Desktop.
Save englishextra/10712436aa14df45d7031fd739bf9dfc to your computer and use it in GitHub Desktop.
/*!
* 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;
};
@optimalisatie
Copy link

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 within t.onloadcssdefined.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment