How to load up CSS files using Javascript?

后端 未结 19 3268
栀梦
栀梦 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: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'])) ();
    

提交回复
热议问题