Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why won't IE implement my CSS rules instantly?

I'm having difficulties with Internet Explorer (even as up-to-date as IE11). I'm trying to write some JavaScript that will allow me to dynamically create a style sheet, add it to the document and manipulate styles, most of which is based on the article that David Walsh wrote. He had the idea of setting the media attribute of the created style tag so legacy browsers will simply ignore rules that they can't support - an idea that I really like, but one that's causing me a few problems.

When I create a style tag with a media attribute more complicated than "screen", Firefox and Chrome will apply the new rules instantly (assuming the media query matches), but IE will not until some kind of page repaint is triggered (resizing the page seems the most effective).

I've created a fiddle to better demonstrate the issue. I'm seeing the results panel having a green background in Firefox and Chrome but red in IE until the repaint is forced. As for actually forcing a repaint, I've tried a few tricks to no success:

  • document.body.className = document.body.className;
  • element.appendChild(document.createTextNode(' '));
  • document.body.style.width = (previousWidth + 1) + 'px'
  • Simplifying the media query to all and (min-width: 10px) and even just (min-width: 10px)

My question is "How can I get IE to implement the styles when they're added?" (or at least, as close to the time their added a possible, I can live with a setTimeout being needed)

I'm using jQuery on the site itself so I'll accept a jQuery answer, but I'd prefer one without a library dependancy so I better understand what's causing the issue and how to resolve it.

like image 468
James Long Avatar asked May 22 '14 09:05

James Long


1 Answers

If you disable line 65 of the javascript it appears to work:

// Webkit hack.
// element.appendChild(document.createTextNode(''));

Since this is apparently a hack, perhaps it can be removed, or worked around more elegantly.

Fiddle

like image 85
graphicdivine Avatar answered Sep 24 '22 21:09

graphicdivine