是否有可能导入css样式表到一个html页面使用Javascript?如果是,该怎么做呢?

p.s. javascript将托管在我的网站上,但我希望用户能够把他们的网站的<头>标签,它应该能够导入一个css文件托管在我的服务器到当前的网页。(CSS文件和javascript文件都将托管在我的服务器上)。


当前回答

如果你想知道(或等待)直到样式本身加载,这是有效的:

// 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 = () => resolve();
    link.onerror = () => reject();
    link.href = url;

    let headScript = document.querySelector('script');
    headScript.parentNode.insertBefore(link, headScript);
  });
};

用法:

fetchStyle(url)
 .then(
   () => console.log("style loaded succesfully"),
   () => console.error("style could not be loaded"),
);

其他回答

use:

document.getElementById("of head/body tag")
        .innerHTML += '<link rel="stylesheet" type="text/css" href="style.css">';

下面是用于加载JS和/或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'])) ();

你听说过《承诺》吗?它们适用于所有现代浏览器,而且使用起来相对简单。看看这个简单的方法,将css注入到html头部:

function loadStyle(src) {
    return new Promise(function (resolve, reject) {
        let link = document.createElement('link');
        link.href = src;
        link.rel = 'stylesheet';

        link.onload = () => resolve(link);
        link.onerror = () => reject(new Error(`Style load error for ${src}`));

        document.head.append(link);
    });
}

你可以这样实现它:

window.onload = function () {
    loadStyle("https://fonts.googleapis.com/css2?family=Raleway&display=swap")
        .then(() => loadStyle("css/style.css"))
        .then(() => loadStyle("css/icomoon.css"))
        .then(() => {
            alert('All styles are loaded!');
        }).catch(err => alert(err));
}

这真的很酷,对吧?这是一种使用Promises来决定样式优先级的方法。

要查看多风格加载实现,请参见:https://stackoverflow.com/a/63936671/13720928

如果你使用jquery:

$('head').append('<link rel="stylesheet" type="text/css" href="style.css">');

可以用于这个YUI库,也可以使用本文实现