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

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


当前回答

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

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

其他回答

我想分享一种方法,不仅加载css,但所有的资产(js, css,图像)和处理onload事件的一堆文件。async-assets-loader。请看下面的例子:

<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> 

根据async-assets-loader文档

下面是一种“老派”的方法,希望它适用于所有浏览器。理论上,你可以使用setAttribute不幸的是,IE6并不一贯支持它。

var cssId = 'myCss';  // you could encode the css path itself to generate id..
if (!document.getElementById(cssId))
{
    var head  = document.getElementsByTagName('head')[0];
    var link  = document.createElement('link');
    link.id   = cssId;
    link.rel  = 'stylesheet';
    link.type = 'text/css';
    link.href = 'http://website.example/css/stylesheet.css';
    link.media = 'all';
    head.appendChild(link);
}

这个例子检查CSS是否已经添加,所以只添加一次。

将该代码放入JavaScript文件中,让最终用户简单地包含JavaScript,并确保CSS路径是绝对的,以便从服务器加载它。

VanillaJS

下面是一个例子,使用纯JavaScript注入一个CSS链接到head元素基于URL的文件名部分:

<script type="text/javascript">
var file = location.pathname.split( "/" ).pop();

var link = document.createElement( "link" );
link.href = file.substr( 0, file.lastIndexOf( "." ) ) + ".css";
link.type = "text/css";
link.rel = "stylesheet";
link.media = "screen,print";

document.getElementsByTagName( "head" )[0].appendChild( link );
</script>

在结束头部标记之前插入代码,CSS将在页面呈现之前加载。使用外部JavaScript (.js)文件将导致出现非样式内容(FOUC)的Flash。

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

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

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

在现代浏览器中,您可以使用这样的promise。创建一个带有promise的loader函数:

function LoadCSS( cssURL ) {

    // 'cssURL' is the stylesheet's URL, i.e. /css/styles.css

    return new Promise( function( resolve, reject ) {

        var link = document.createElement( 'link' );

        link.rel  = 'stylesheet';

        link.href = cssURL;

        document.head.appendChild( link );

        link.onload = function() { 

            resolve(); 

            console.log( 'CSS has loaded!' ); 
        };
    } );
}

显然,你想在CSS加载后完成一些事情。你可以像这样调用CSS加载后需要运行的函数:

LoadCSS( 'css/styles.css' ).then( function() {

    console.log( 'Another function is triggered after CSS had been loaded.' );

    return DoAfterCSSHasLoaded();
} );

如果你想深入了解它是如何工作的,有用的链接:

官方承诺文件

有关承诺的有用指南

一个很棒的关于承诺的介绍视频