最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - Is it good to edit the css dynamically with javascript injecting css code in the head? - Stack Overflow

programmeradmin1浏览0评论

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?

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?

Share Improve this question asked Jan 11, 2014 at 15:58 PaoloPaolo 15.8k27 gold badges72 silver badges94 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 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.

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 bee 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/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/en-US/docs/Web/API/MutationObserver

    This is an awesome way to handle the problem, but unfortunately it is not patible 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./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...

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).
发布评论

评论列表(0)

  1. 暂无评论