I have a script that detects a button click on which it will attach a CSS stylesheet to the "head" with jQuery like so:
const link = "<link class='listcss' rel='stylesheet' href='http://....list.css'>";
$("head").append(link);
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();
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:
I tried these options:
Does not work:
link.onload = function () {
CSSDone();
}
Does not work:
if (link.addEventListener) {
link.addEventListener('load', function() {
CSSDone();
}, false);
}
Does not work:
link.onreadystatechange = function() {
var state = link.readyState;
if (state === 'loaded' || state === 'complete') {
link.onreadystatechange = null;
CSSDone();
}
};
Does not work:
$(window).load(function () {
CSSDone();
});
Does not work:
$(window).bind("load", function() {
CSSDone();
});
Believe me. Nothing works......
**One workaround:**
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.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…