动态加载CSS样式表并等待其加载 [英] Dynamically load css stylesheet and wait for it to load
问题描述
我有一个脚本,可以在按下这样的按钮时加载CSS样式表:
I have a script where I load a css stylesheet when pressing a button like this:
link = "<link class='listcss' rel='stylesheet' href='http://....list.css'>";
$("head").append(link);
然后我需要根据CSS的width和height属性进行一些计算:
Then I need to do some calculations based on the css width and height properties:
function CSSDone(){
if($(window).width()>640){
$(".grid-item").css({"height":$(".grid-item").width()*0.2});
$(".grid_item_img").css({"height":$(".grid-item").width()*0.2});
console.log("a");
}else{
$(".grid-item").css({"height":$(".grid-item").width()*0.33});
$(".grid_item_img").css({"height":$(".grid-item").width()*0.33});
console.log("b");
}
}
CSSDone();
但是,如果我启动CSSDone();在添加样式表之后,计算便会在加载CSS之前进行. 我在网上疯狂地搜索,但我尝试的所有方法均无效:
However, if I launch CSSDone(); right after adding the stylesheet, the calculations happen before the css is loaded. I searched the web like crazy but everything I tried doesn't work:
我尝试了以下选项: 1)不起作用:
I tried these options: 1) Does not work:
link.onload = function () {
CSSDone();
}
2)不起作用:
if (link.addEventListener) {
link.addEventListener('load', function() {
CSSDone();
}, false);
}
3)不起作用:
link.onreadystatechange = function() {
var state = link.readyState;
if (state === 'loaded' || state === 'complete') {
link.onreadystatechange = null;
CSSDone();
}
};
4)不起作用:
$(window).load(function () {
CSSDone();
});
5)不起作用:
$(window).bind("load", function() {
CSSDone();
});
相信我.什么都行不通......
一种解决方法:
Believe me. Nothing works......
One workaround:
我将css加载到DOM中,然后立即用jQuery将其立即删除.这样,以后将链接添加到头部时,它足够快.
I load the css in the DOM and immidiately remove it again with jQuery. That way when adding the link to the head later it's fast enough.
推荐答案
您需要在头部插入一个link
节点,然后将onload
事件附加到该节点.在您的代码链接中是一个字符串.有关如何实现所需内容的信息,请参见下面的示例代码.
You need to insert a link
node in the head and then attach onload
event to that. In your code link is a String. See sample code below on how to implement what you want.
var link = document.createElement('link');
link.setAttribute("rel", "stylesheet");
link.setAttribute("type", "text/css");
link.onload = function(){ CSSDone(); }
link.setAttribute("href", 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css');
document.getElementsByTagName("head")[0].appendChild(link);
这篇关于动态加载CSS样式表并等待其加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!