jQuery Append CSS File and Wait until Loaded?

前端 未结 2 1396
醉梦人生
醉梦人生 2021-01-05 07:47

I am trying to append a css file using

$(\'head\').append(\'\');

That wo

相关标签:
2条回答
  • 2021-01-05 07:54

    The first thing to do is to put your functions inside the ready method, that will execute those functions after the DOM has loaded.

    <script type="text/javascript">
      jQuery(document).ready(function() {
        // Your functions come here
    });
    </script>
    

    Then just put your script before the </body>. This way the append will be triggered just as the dom loads.

    <script type="text/javascript">
    $('head').append();
    </script>
    

    Another aproach is to use the load event:
    Check this link with the working example, within it I've set the body with a green background, it loads the stackoverflow stylesheet that when finishes loading it changes the body to white.
    http://jsfiddle.net/CQbqA/1/

    0 讨论(0)
  • 2021-01-05 07:55

    Just check when one of the rules of the new CSS has been applied:

    $('head').append('<link rel="stylesheet" href="http://cdn.sstatic.net/stackoverflow/all.css?v=d4a5c7ca0d4c" type="text/css" />');
    
    var fakeListener = setInterval(function(){
        if($("body").css("text-align")=== "center"){
            clearInterval(fakeListener)
            // What you want to do after it loads
        }
    },50)
    

    (That is a working example)

    0 讨论(0)
提交回复
热议问题