Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically loading css stylesheet doesn't work on IE

I dynamically load a css stylesheet (with a little help from jQuery) like this:

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

like image 610
pistacchio Avatar asked Jul 26 '09 16:07

pistacchio


2 Answers

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

See the MSDN article on createStyleSheet for a few more details.

url = 'style.css'; if (document.createStyleSheet) {     document.createStyleSheet(url); } else {     $('<link rel="stylesheet" type="text/css" href="' + url + '" />').appendTo('head');  } 
like image 107
Rex M Avatar answered Oct 01 '22 13:10

Rex M


You need to set the href attr last and only after the link elem is appended to the head:

$('<link>')   .appendTo('head')   .attr({type : 'text/css', rel : 'stylesheet'})   .attr('href', '/css/your_css_file.css'); 

Update

Nowadays the only purpose of IE and Edge is to download Chrome, so I recommend NOT bloating your code with custom support for IE or Edge and rather just ignoring their existence.

like image 36
ekerner Avatar answered Oct 01 '22 11:10

ekerner