3

Is it "legal" and working cross browser the injection of CSS code in the head in order to set/change permanently the properties of something?

For example (using jQuery):

$('head').append('<style>.myclass { background: #f00;}</style>');

I've tried it in Safari 7 and works.

Is it ok and cross browser or is a hack to avoid?

Are there any drawbacks?

3 Answers 3

4

Yes, it is legal - and it will be faster than $(".myclass").css({background: "#FF0"}) because you only interact with the DOM once rather than N times (where N is the number of .myclass elements on the page.) Also, it will be applied to future .myclass elements automatically.

The disadvantage is that you can run into specificity issues, so you have to make sure to architect your CSS in a way that will ensure that you can override the background with a single class selector. (jQuery's css function, since it sets the element's style attribute directly, has some of the highest specificity by default and so avoids this particular problem).

For example, if you had this CSS somewhere in your linked styles:

#some-id .myclass { background: #000; }

then the DOM-heavy $(".myclass").css would override the background, while the dynamically injected style (injecting just .myclass { background: #FF0; } would not).

The other disadvantage is that old-IE (<=8) only allows you to create 31 of these "dynamic" style sheets. In IE >= 9, this is not a problem.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you Sean. Could you please explain better (or make an example of) the "specificity issue"? As jQuery set the style attributes directly it overrides specifications from the CSS..
@Paolo - example added.
1

I think you are facing a 4 solutions scenario.

None of these is either really elegant or perfect, but here are my 2 cents:

  1. Inject the css in the head section of your HTML

    This is exactly what you suggested in your question. This solution works well, but only if the modification occurs once. If you need to apport many subsequent modification the head section of your HTML might become crowded.

  2. You can detect the insertion of the DOM objects with Javascript and keep them in-sync

    Here you are a JSFiddle that does exactly this: http://jsfiddle.net/ITnok/9FQVa/28/

    This solution works fine if you (and may be your user) are supposed to do many changes spread in time, BUT only if you have control on DOM object insertion: the key is to create a custom event to trigger each time you insert a new object.

    Here the chunk of code from the JSFiddle that handle the custom event:

    //    This event is the key to keep CSS in sync... in realtime!
    $( document )
        .on( 'mickeymouseadded', '.mickeymouse', function( e ) {
            $( this )
                .attr(
                    'style',
                    $( this )
                        .siblings( ':first' )
                        .attr( 'style' )
                );
        } );
    
  3. You can use MutationObserver (new version of old and deprecated Mutation Events)

    Here you are the link to the documentation: https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver

    This is an awesome way to handle the problem, but unfortunately it is not compatible with old version of Interdict Exploder (Oops, sorry for the trolling! :-) ). Only IE11 supports them.

    This method works even if object insertion is out of your direct control, you are not able to create custom events or do not want to.

  4. You can use a jQuery plugin called livequery

    Here you are the link to the Github repo of jQuery livequery: https://github.com/brandonaaron/livequery

    Never tried this very plugin, but it looks like it might be a good solution to query the DOM and identify what need to be modified and kept in-sync.

All these solution are based on the presence of Javascript

but as far as I know from what you told us this would not be an issue for you! ;-)

Hope it helps...

Comments

-1

If the user disabled javascript in his browser (faster to load pages), it should be a problem.

You should:

  • write the fixed css of your site in the css files
  • use js only if you have some parsing to do (if you want to insert in each <span class="to_change">...</span> some css per example).

3 Comments

it's not an issue, it's a javascript webapp. ...and if a user disables javascript I think will be able to do very little on today's internet...
The OP asked specifically about editing css dynamically. If the user has disabled javascript, then the only solution for dynamically editing styles is to ask them nicely to re-enable it.
A website has to be clear without javascript. Performing css modification is not a good thing, only if you add content in your page: per example: inserting the css of a slideshow, if your js script allow you to customise your slideshow. You should have told before it was a javascript webapp.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.