I want to lazy load a css file, and then have javascript modify a page after said css loaded. To that end, I'm using this approach, as illustrated here:
lazyLoadCSS = function (pathToStyleSheet, options, callback) {
var stylesheet = document.createElement('link');
stylesheet.href = pathToStyleSheet;
stylesheet.rel = 'stylesheet';
stylesheet.type = 'text/css';
// temporarily set media to something inapplicable to ensure
// it'll fetch without blocking render
stylesheet.media = 'only x';
// set the media back when the stylesheet loads
stylesheet.onload = function() {
stylesheet.media = 'all';
// here be callbacks...
callback();
};
document.getElementsByTagName('head')[0].appendChild(stylesheet);
};
So, the idea is, javascript fetches the CSS, but smuggles it in as 'only x' so the browser doesn't think it needs to wait for the file before rendering the rest of the page, which is the whole point. This approach seems to be pretty standard and the above code does work...mostly.
The only problem is the callback. It happens after the CSS is loaded, but before the styles have been applied to the document.
If I put a timer on the callback, like so:
window.setTimeout(function(){
callback();
}, 2000);
then everything works exactly the way it should (only slow).
Question is, how can I wait not only for the CSS to load, but also to be applied before I run the callback()
?