How to load up CSS files using Javascript?

后端 未结 19 3140
栀梦
栀梦 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:53
    var elem = document.createElement('link');
    elem.rel = ' stylesheet'
    elem.href= 'style.css';//Link of the css file
    document.head.appendChild(elem);
    
    0 讨论(0)
  • 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);
      });
    };
    
    0 讨论(0)
  • 2020-11-21 07:55

    Use this code:

    var element = document.createElement("link");
    element.setAttribute("rel", "stylesheet");
    element.setAttribute("type", "text/css");
    element.setAttribute("href", "external.css");
    document.getElementsByTagName("head")[0].appendChild(element);
    
    0 讨论(0)
  • 2020-11-21 07:55

    Below a full code using for loading JS and/or CSS

    function loadScript(directory, files){
      var head = document.getElementsByTagName("head")[0]
      var done = false
      var extension = '.js'
      for (var file of files){ 
        var path = directory + file + extension 
        var script = document.createElement("script")
        script.src = path        
        script.type = "text/javascript"
        script.onload = script.onreadystatechange = function() {
            if ( !done && (!this.readyState ||
                this.readyState == "loaded" || this.readyState == "complete") ) {
                done = true
                script.onload = script.onreadystatechange = null   // cleans up a little memory:
                head.removeChild(script)  // to avoid douple loading
            }
      };
      head.appendChild(script) 
      done = false
     }
    }
    
    function loadStyle(directory, files){
      var head = document.getElementsByTagName("head")[0]
      var extension = '.css'
      for (var file of files){ 
       var path = directory + file + extension 
       var link = document.createElement("link")
       link.href = path        
       link.type = "text/css"
       link.rel = "stylesheet" 
       head.appendChild(link) 
     }
    }
    
    (() => loadScript('libraries/', ['listen','functions', 'speak', 'commands', 'wsBrowser', 'main'])) ();
    (() => loadScript('scripts/', ['index'])) ();
    
    (() => loadStyle('styles/', ['index'])) ();
    
    0 讨论(0)
  • 2020-11-21 07:56

    I'd like to share one more way to load not only css but all the assets (js, css, images) and handle onload event for the bunch of files. It's async-assets-loader. See the example below:

    <script src="https://unpkg.com/async-assets-loader"></script>
    <script>
    var jsfile = "https://code.jquery.com/jquery-3.4.1.min.js";
    var cssfile = "https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css";
    var imgfile = "https://logos.keycdn.com/keycdn-logo-black.png";
    var assetsLoader = new asyncAssetsLoader();
    assetsLoader.load([
          {uri: jsfile, type: "script"},
          {uri: cssfile, type: "style"},
          {uri: imgfile, type: "img"}
        ], function () {
          console.log("Assets are loaded");
          console.log("Img width: " + assetsLoader.getLoadedTags()[imgfile].width);
        });
    </script> 
    

    According to the async-assets-loader docs

    0 讨论(0)
  • 2020-11-21 07:57

    If you use jquery:

    $('head').append('<link rel="stylesheet" type="text/css" href="style.css">');
    
    0 讨论(0)
提交回复
热议问题