jQuery 追加 CSS 文件并等待加载?加载、文件、jQuery、CSS

2023-09-07 09:56:30 作者:宇宙猛男、

我正在尝试使用

$('head').append('<link rel="stylesheet" href="style2.css" type="text/css"/>');

这很好用 - 但是,我有一些在添加 css 之后运行的函数,我想不出一种方法让这些函数等到这个文件完成加载?

That works great - however, I have some functions that run AFTER the css has been added and I can't figure out a way for these to wait until this file has finished loading ?

我该怎么做?

推荐答案

只需检查新 CSS 的规则之一何时应用即可:

Just check when one of the rules of the new CSS has been applied:

$('head').append('<link rel="stylesheet" href="http://cdn.sstatic.net/stackoverflow/all.css?v=d4a5c7ca0d4c" type="text/css" />');

var fakeListener = setInterval(function(){
    if($("body").css("text-align")=== "center"){
        clearInterval(fakeListener)
        // What you want to do after it loads
    }
},50)

(这是一个工作示例)