Dynamic CSS stylesheet loading does not work on IE

I am dynamically loading a CSS stylesheet (with a little jQuery help), for example:

var head = document.getElementsByTagName('head')[0]; $(document.createElement('link')) .attr({ type: 'text/css', href: '../../mz/mz.css', rel: 'stylesheet' }) .appendTo(head); 

This works fine in Firefox and Google Chrome, but not in IE.

Any help? Thanks

+71
javascript jquery html css internet-explorer
Jul 26 '09 at 16:19
source share
6 answers

Once IE has processed all the styles loaded by the page, the only reliable way to add another stylesheet is document.createStyleSheet(url)

See the MSDN article in the createStyleSheet file for more information.

 url = 'style.css'; if (document.createStyleSheet) { document.createStyleSheet(url); } else { $('<link rel="stylesheet" type="text/css" href="' + url + '" />').appendTo('head'); } 
+118
Jul 26 '09 at 16:25
source share

You need to set the last href attr value and only after adding the elem element to the head:

 $('<link>') .appendTo('head') .attr({type : 'text/css', rel : 'stylesheet'}) .attr('href', '/css/your_css_file.css'); 
+37
Apr 04 2018-11-11T00:
source share

This also works in IE:

 var link = document.createElement ('link');
 link.rel = 'stylesheet';
 link.type = 'text / css';
 link.href = '/includes/style.css';
 document.getElementsByTagName ('head') [0] .appendChild (link);
+3
Feb 03 '11 at 20:51
source share

It may also have something to do with it - taken from Microsoft Support Article :

The styles on the web page are missing or do not look correctly when loading the page in versions of Microsoft Internet Explorer ...

... This problem occurs due to the fact that in Internet Explorer:

  • All style tags after the first 31 style tags are not applied.

  • All style rules after the first 4095 rules do not apply.

  • For pages that use the @import rule to constantly import external style sheets that import other style sheets, style sheets that have more than three depth levels are ignored.

+2
Jul 07 '11 at 10:22
source share

It seems that

 $('<link rel="stylesheet" type="text/css" href="' + url + '" />').appendTo('head'); 

also works in IE, as long as the URL is a full URI, including protocol ...

+1
Nov 29 '12 at 7:30
source share

Open ie8 without debugging. When you get to the point of the dynamic stylesheet ... open the debugger and voila, they should be there.

0
Apr 21 '16 at 14:28
source share



All Articles