CSS样式表完成加载后如何运行函数 [英] How to run a function when CSS stylesheet finishes loading

查看:118
本文介绍了CSS样式表完成加载后如何运行函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How do I run a function when a 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的

您可以通过观察要触发的load事件来确定何时加载样式表;同样,您可以通过观察error事件来检测在处理样式表时是否发生了错误:

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

注意:load事件在样式表及其所有导入的内容被加载并解析后立即触发,并且在样式开始应用于内容之前立即触发.

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样式表完成加载后如何运行函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆