How to asynchronously load CSS using jQuery?

后端 未结 8 1162
难免孤独
难免孤独 2020-12-07 23:22

I want to use jQuery to asynchronously load CSS for a document.

I found this sample, but this doesn\'t seem to work in IE:



        
8条回答
  •  一生所求
    2020-12-07 23:43

    Here's a method for asynchronous stylesheet loading that doesn't block page render that worked for me:

    https://github.com/filamentgroup/loadCSS/blob/master/loadCSS.js

    Reduced example of the code linked above, based on lonesomeday's answer

    var stylesheet = document.createElement('link');
    stylesheet.href = '/inc/body/jquery/css/start/jquery-ui-1.8.10.custom.css';
    stylesheet.rel = 'stylesheet';
    stylesheet.type = 'text/css';
    // temporarily set media to something inapplicable to ensure it'll fetch without blocking render
    stylesheet.media = 'only x';
    // set the media back when the stylesheet loads
    stylesheet.onload = function() {stylesheet.media = 'all'}
    document.getElementsByTagName('head')[0].appendChild(stylesheet);
    

提交回复
热议问题