Home  >  Article  >  Web Front-end  >  Solution to using javascript to dynamically load CSS in IE8_javascript skills

Solution to using javascript to dynamically load CSS in IE8_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:44:131435browse

As we all know, front-end developers are eager to kick IE developers. The reputation of IE developers is no less than that of GFW developers. If they ruin the market without conscience, everyone will punish them. But in local markets like China The share is there, and we have no choice but to bow to reality.

Recently, our product needs to dynamically load a piece of CSS in the browser. The previous code was used directly:

Copy the code The code is as follows:

var bubbleCss = document.createElement('style');
bubbleCss.type = 'text/css';
bubbleCss.innerHTML = blc_conf.bubbleStyle;
document.getElementsByTagName('head')[0].appendChild(bubbleCss);

However, this is only supported by IE9 and will cause problems under IE8. I never noticed this until the recent reconstruction. I found out later when I did a complete test.
I found a trick online and tried it. It works, but there are some problems
Copy the code The code is as follows:

window.bc_bubble_css = blc_conf.bubbleStyle;
document.createStyleSheet("javascript:bc_bubble_css");

Here you can create a style defined by the variable bc_bubble_css, but due to the increasing popularity of HTML5, Our css also has some css3 selectors mixed in. Using this method will cause IE8's parser to throw an exception when parsing the css3 selector and stop parsing subsequent css. This makes the css only half loaded. The methods found online are all using StyleSheet. Type addRule to add, but this requires specifying the css2 selector and style yourself.
Therefore, you need to disassemble a single rule from CSS and then call addRule in sequence. Example:
Copy code The code is as follows:

var s = document.createStyleSheet();
var rules = blc_conf.bubbleStyle.replace(//*[ ^*]**//g, "").replace(/@[^{]*{/g, '').match(/[^{}] {[^}] }/g);
for(var i = 0; i < rules.length; i ) {
var m = rules[i].match(/(.*)s*{s*(.*)}/);
if(m) {
try {
s.addRule(m[1], m[2]);
} catch(e) {
}
}
}

There are two replacements at the beginning, which remove the gaze and some css3 selectors respectively. However, there are still some selectors that have slipped through the net and need to be caught later by try catch.

Also, I once again despise the people who designed the IE interface

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn