I have a code (it’s actually not mine, but SlickGrid ) that creates the <style> element, inserts it into the DOM, and then immediately tries to find the new stylesheet in the document.styleSheets collection.
In WebKit, this sometimes fails. I have no idea what the circumstances are, but this is nothing that is consistently reproducible. I decided that I could get around this by changing the code, so the StyleSheet object is not checked before the load event in the style element, for example:
$style = $("<style type='text/css' rel='stylesheet' />").appendTo($("head")); var rules = ...;// code to create the text of the rules here if ($style[0].styleSheet) { // IE $style[0].styleSheet.cssText = rules.join(" "); } else { $style[0].appendChild(document.createTextNode(rules.join(" "))); } $style.bind('load', function() { functionThatExpectsTheStylesheet(); });
and functionThatExpectsTheStylesheet tries to find the actual style sheet object like this:
var sheets = document.styleSheets; for (var i = 0; i < sheets.length; i++) { if ((sheets[i].ownerNode || sheets[i].owningElement) == $style[0]) { stylesheet = sheets[i]; break; } }
but sometimes even at this point the style sheet object is not found.
So my question is this:
- Does the
load event not guarantee that the styleSheet object will be available? This is mistake? - If not, is there another condition that I can use, or do I just need to do it using timeouts?
- Or are there some problems with how I bind the load event and what is my problem?
javascript jquery dom webkit
Dan
source share