是否有可能导入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"),
);

其他回答

元素。insertAdjacentHTML有很好的浏览器支持,可以在一行中添加一个样式表。

document.getElementsByTagName("head")[0].insertAdjacentHTML(
    "beforeend",
    "<link rel=\"stylesheet\" href=\"path/to/style.css\" />");

YUI库可能就是您正在寻找的。它还支持跨域加载。

如果你使用jquery,这个插件做同样的事情。

下面是jQuery的元素创建方法(我的偏好)和回调onLoad的方法:

var css = $("<link>", {
  "rel" : "stylesheet",
  "type" :  "text/css",
  "href" : "style.css"
})[0];

css.onload = function(){
  console.log("CSS IN IFRAME LOADED");
};

document
  .getElementsByTagName("head")[0]
  .appendChild(css);

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

// 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"),
);

有一个通用的jquery插件,可以按需加载css和JS文件的同步和异步。 它还可以跟踪已经加载的内容:) 参见:http://code.google.com/p/rloader/