如何在 CSS 样式表完成加载时 运行 一个函数

How to run a function when CSS stylesheet finishes loading

如何在样式表完成加载后 运行 函数?

这是我的代码..

var d = document,
    css = d.head.appendChild(d.createElement('link'))

css.rel = 'stylesheet';
css.type = 'text/css';
css.href = "https://unpkg.com/tachyons@4.10.0/css/tachyons.css"

根据 MDN 的 <link>: The External Resource Link element

You can determine when a style sheet has been loaded by watching for a load event to fire on it; similarly, you can detect if an error has occurred while processing a style sheet by watching for an error event:

<script>
var myStylesheet = document.querySelector('#my-stylesheet');

myStylesheet.onload = function() {
  // Do something interesting; the sheet has been loaded
}

myStylesheet.onerror = function() {
  console.log("An error occurred loading the stylesheet!");
}
</script>

<link rel="stylesheet" href="mystylesheet.css" id="my-stylesheet">

Note: The load event fires once the stylesheet and all of its imported content has been loaded and parsed, and immediately before the styles start being applied to the content.

这是为接受 CSS onload 的现代浏览器优化的 cross-browser 解决方案。它可以追溯到 2011 年,当时只有 Opera 和 Internet Explorer 在 css 上分别支持 onload 事件和 onreadystatechange。请参阅下面的 link。

var d = document,
    css = d.head.appendChild(d.createElement('link')),
    src = "https://unpkg.com/tachyons@4.10.0/css/tachyons.css"

css.rel = 'stylesheet';
css.type = 'text/css';
css.href = src

在加载程序之后添加这个

if (typeof css.onload != 'undefined') css.onload = myFun;
else {
    var img = d.createElement("img");
    img.onerror = function() {
      myFun();
      d.body.removeChild(img);
    }
    d.body.appendChild(img);
    img.src = src;
}

function myFun() {
    /* ..... CONTINUE CODE HERE ..... */
}

答案基于 this link 说:

What happens behind the scenes is that the browser tries to load the CSS in the img element and, because a stylesheet is not a type of image, the img element throws the onerror event and executes our function. Thankfully, browsers load the entire CSS file before determining its not an image and firing the onerror event.