How to run a function when CSS stylesheet finishes loading

别等时光非礼了梦想. 提交于 2020-01-06 05:43:04

问题


How do I run a function when a stylesheet finishes loading?

Here is my code..

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"

回答1:


According to MDN's <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.




回答2:


This is a cross-browser solution optimized for modern browsers accepting CSS onload. It works back to 2011 when only Opera and Internet Explorer supported the onload event and onreadystatechange respectively on css. See link below.

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

Add this after the loader

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 ..... */
}

The answer is based on this link that say:

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.



来源:https://stackoverflow.com/questions/56118483/how-to-run-a-function-when-css-stylesheet-finishes-loading

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!