How to load up CSS files using Javascript?

后端 未结 19 3272
栀梦
栀梦 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条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-21 07:54

    If you want to know (or wait) until the style itself has loaded this works:

    // this will work in IE 10, 11 and Safari/Chrome/Firefox/Edge
    // add ES6 poly-fill for the Promise, if needed (or rewrite to use a callback)
    
    let fetchStyle = function(url) {
      return new Promise((resolve, reject) => {
        let link = document.createElement('link');
        link.type = 'text/css';
        link.rel = 'stylesheet';
        link.onload = function() { resolve(); console.log('style has loaded'); };
        link.href = url;
    
        let headScript = document.querySelector('script');
        headScript.parentNode.insertBefore(link, headScript);
      });
    };
    

提交回复
热议问题