'How to catch a "load" event on STYLE tag with IE?
Let's say I have the following code:
var style = $("<style/>")
.html("body{background:grey; color:white;} /*and more CSS style*/")
.on("load", function () {
console.log("The New style injection has finished to load!");
});
$("head").append(style);
On Chrome, Safari and Firefox browsers the load
event triggers on time and works perfectly, exactly as expected.
But on Internet Explorer (any version) it doesn't trigger the load
event at all!
Why doesn't it works on IE?
What is the solution for IE (if any)?
An example that works on all browsers except IE, can be found here: http://jsfiddle.net/KWHyZ/2/
Solution 1:[1]
I propose a different way altogether of tackling this problem, though I don't have a page with enough css to test it with.
Rather than waiting for the load event to be fired, which, appears not to happen - why not make the content hidden by default, only making it visible with the added css?
That is to say, the following provides an alert and a message on the console in Chrome, but it's never fired in IE. However, since the (pre-existing) css appears before the <body>
tag, page remains 'blank' until the dynamically added css has loaded.
JS
window.addEventListener('load', mInit, false);
function onStyleLoaded()
{
var mStr = "The New style injection has finished to load!";
console.log(mStr);
alert(mStr);
}
function mInit()
{
var style = newEl('style');
style.addEventListener('load', onStyleLoaded, false);
style.innerHTML = ".styleMe{font-weight: bold; color: red;} body{visibility:visible;}";
document.head.appendChild(style);
}
CSS
body
{
visibility: hidden;
}
HTML
<body>
<div class='styleMe'>Style this stuff!</div>
</body>
Solution 2:[2]
If you're adding only a couple of CSS rules - do them individually:
$('body').css({background:'#000', color:'#fff'});
$('#element').css({color:'#000', textDecoration:'underline'});
//etc...
If you're adding a bunch of stuff, then create a stylesheet and load it dynamically onto the page:
$('<link/>')
.attr('href','http://example.com/urltostylesheet.css')
.attr('rel','stylesheet')
.attr('type','text/css')
.appendTo($('head'))
.on('load',function() {
// do stuff
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Andre Figueiredo |