How to load up CSS files using Javascript?

后端 未结 19 3333
栀梦
栀梦 2020-11-21 07:51

Is it possible to import css stylesheets into a html page using Javascript? If so, how can it be done?

P.S the javascript will be hosted on my site, but I want users

19条回答
  •  Happy的楠姐
    2020-11-21 08:15

    Here's a way with jQuery's element creation method (my preference) and with callback onLoad:

    var css = $("", {
      "rel" : "stylesheet",
      "type" :  "text/css",
      "href" : "style.css"
    })[0];
    
    css.onload = function(){
      console.log("CSS IN IFRAME LOADED");
    };
    
    document
      .getElementsByTagName("head")[0]
      .appendChild(css);
    

提交回复
热议问题