CSS 如何判断CSS是否已加载?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10537039/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to determine if CSS has been loaded?
提问by Erik Funkenbusch
How can i Assert that the CSS for a page has successfully loaded and applied its styles in Watin 2.1?
我如何断言页面的 CSS 已成功加载并在 Watin 2.1 中应用其样式?
回答by ShadowScripter
After doing some research and writing up my answer, I stumbled upon this linkthat explains everything you need to know about CSS, when it is loaded and how you can check for it.
在做了一些研究并写下我的答案之后,我偶然发现了这个链接,它解释了你需要了解的关于 CSS 的一切,它何时被加载以及如何检查它。
The link provided explains it so well, in fact, that I'm adding some quotes from it for future reference.
If you're curious, my answer was going to be #2 and a variation of #4.
提供的链接很好地解释了它,事实上,我正在添加一些引用以供将来参考。
如果您好奇,我的答案将是#2 和#4 的变体。
When is a stylesheet really loaded?
什么时候真正加载样式表?
...
...
With that out of the way, let's see what we have here.
顺便说一下,让我们看看这里有什么。
// my callback function
// which relies on CSS being loaded function
CSSDone() {
alert('zOMG, CSS is done');
};
// load me some stylesheet
var url = "http://tools.w3clubs.com/pagr/1.sleep-1.css",
head = document.getElementsByTagName('head')[0],
link = document.createElement('link');
link.type = "text/css";
link.rel = "stylesheet";
link.href = url;
// MAGIC
// call CSSDone() when CSS arrives
head.appendChild(link);
Options for the magic part, sorted from nice-and-easy to ridiculous
魔法部分的选项,从简单到可笑
- listen to link.onload
- listen to link.addEventListener('load')
- listen to link.onreadystatechange
- setTimeout and check for changes in document.styleSheets
- setTimeout and check for changes in the styling of a specific element you create but style with the new CSS
- 听link.onload
- 听 link.addEventListener('load')
- 听link.onreadystatechange
- setTimeout 并检查 document.styleSheets 中的更改
- setTimeout 并检查您创建的特定元素的样式更改,但使用新 CSS 设置样式
5th option is too crazy and assumes you have control over the content of the CSS, so forget it. Plus it checks for current styles in a timeout meaning it will flush the reflow queue and can be potentially slow. The slower the CSS to arrive, the more reflows. So, really, forget it.
第 5 个选项太疯狂了,假设您可以控制 CSS 的内容,所以忘记它。此外,它会在超时时检查当前样式,这意味着它将刷新回流队列并且可能会很慢。CSS 到达越慢,回流越多。所以,真的,忘记它。
So how about implementing the magic?
那么如何实现魔法呢?
// MAGIC
// #1
link.onload = function () {
CSSDone('onload listener');
};
// #2
if (link.addEventListener) {
link.addEventListener('load', function() {
CSSDone("DOM's load event");
}, false);
};
// #3
link.onreadystatechange = function() {
var state = link.readyState;
if (state === 'loaded' || state === 'complete') {
link.onreadystatechange = null;
CSSDone("onreadystatechange");
}
};
// #4
var cssnum = document.styleSheets.length;
var ti = setInterval(function() {
if (document.styleSheets.length > cssnum) {
// needs more work when you load a bunch of CSS files quickly
// e.g. loop from cssnum to the new length, looking
// for the document.styleSheets[n].href === url
// ...
// FF changes the length prematurely :(
CSSDone('listening to styleSheets.length change');
clearInterval(ti);
}
}, 10);
// MAGIC ends
回答by JohnSz
There has been an update to the article lined to by @ShadowScripter. The new method purportedly works in all browsers, including FF.
@ShadowScripter 对文章进行了更新。据称,新方法适用于所有浏览器,包括 FF。
var style = document.createElement('style');
style.textContent = '@import "' + url + '"';
var fi = setInterval(function() {
try {
style.sheet.cssRules; // <--- MAGIC: only populated when file is loaded
CSSDone('listening to @import-ed cssRules');
clearInterval(fi);
} catch (e){}
}, 10);
document.getElementsByTagName('head')[0].appendChild(style);
回答by alonp
After page load you can verify the style on some of your elements something like this:
页面加载后,您可以验证某些元素的样式,如下所示:
var style = browser.Div(Find.ByClass("class")).Style;
Assert.That(Style.Display, Is.StringContaining("none"));
Assert.That(Style.FontSize, Is.EqualTo("10px"));
And etc...
等等...
回答by Hyman Giffin
Since browser compatibility can vary, and new future browser standards subject to change, I would recommend a combination of the onload listener and adding CSS to the style sheet so you can listen for when the HTML elements z-index changes if you are using a single style sheet. Otherwise, use the function below with a new meta tag for each style.
由于浏览器兼容性可能会有所不同,并且未来新的浏览器标准可能会发生变化,我建议将 onload 侦听器和向样式表添加 CSS 相结合,这样如果您使用单个样式表。否则,请使用下面的函数和每个样式的新元标记。
Add the following to the CSS file that you are loading:
将以下内容添加到您正在加载的 CSS 文件中:
#*(insert a unique id for he current link tag)* {
z-index: 0
}
Add the following to your script:
将以下内容添加到您的脚本中:
function whencsslinkloads(csslink, whenload ){
var intervalID = setInterval(
function(){
if (getComputedStyle(csslink).zIndex !== '0') return;
clearInterval(intervalID);
csslink.onload = null;
whenload();
},
125 // check for if it has loaded 8 times a second
);
csslink.onload = function(){
clearInterval(intervalID);
csslink.onload = null;
whenload();
}
}
Example
例子
index.html
:
index.html
:
<!doctype html>
<html>
<head>
<link rel=stylesheet id="EpicStyleID" href="the_style.css" />
<script async href="script.js"></script>
</head>
<body>
CSS Loaded: <span id=result>no</span>
</body>
</html>
script.js
:
script.js
:
function whencsslinkloads(csslink, whenload ){
var intervalID = setInterval(
function(){
if (getComputedStyle(csslink).zIndex !== '0') return;
clearInterval(intervalID);
csslink.onload = null;
whenload();
},
125 // check for if it has loaded 8 times a second
);
csslink.onload = function(){
clearInterval(intervalID);
csslink.onload = null;
whenload();
}
}
/*************************************/
whencsslinkloads(
document.getElementById('EpicStyleID'),
function(){
document.getElementById('result').innerHTML = '<font color=green></font>'
}
)
the_style.css
the_style.css
#EpicStyleID {
z-index: 0
}
PLEASE do notmake your script load synchronously (without the async
attribute) just so you can capture the link's onload event. There are better ways, like the method above.
请不要让您的脚本同步加载(没有async
属性),以便您可以捕获链接的 onload 事件。有更好的方法,比如上面的方法。