admin管理员组文章数量:1336660
I load CSS by:
$('head').append('<link rel="stylesheet" href="style2.css" type="text/css" />');
It works, but I have a function that needs to run after the CSS has been applied, and I don't want use setInterval
for it.
How can I do this ?
I load CSS by:
$('head').append('<link rel="stylesheet" href="style2.css" type="text/css" />');
It works, but I have a function that needs to run after the CSS has been applied, and I don't want use setInterval
for it.
How can I do this ?
Share Improve this question edited Aug 19, 2015 at 4:40 Kaiido 137k14 gold badges258 silver badges324 bronze badges asked Aug 19, 2015 at 2:42 ThuyNguyenThuyNguyen 1,1853 gold badges14 silver badges26 bronze badges 3- stackoverflow./a/8767297/3344111 or stackoverflow./a/26169508/3344111 – Tahir Ahmed Commented Aug 19, 2015 at 2:50
- 3 possible duplicate of jQuery Append CSS File and Wait until Loaded? – bestprogrammerintheworld Commented Aug 19, 2015 at 4:44
- @CVers, none of the solutions in the could be dupe does deal with OP's requirements : "don't use setInterval", accepted answer does this, and "wait until styles are applied", second answer only waits for the document has loaded. – Kaiido Commented Aug 19, 2015 at 7:21
2 Answers
Reset to default 7One solution, if you've got access to the css file you're loading,
is to use the transitionend
event, and to activate a transition, with duration
set to 0.1, from your css.
Like so, you are sure the CSS has been calculated.
style2.css
body{opacity:1;}
index.html
<style>
body{transition : opacity 0.1s linear; opacity:.9};
</style>
<body>
...
<script>
document.body.addEventListener('transitionend', function(){
alert('done');
}, false);
$('head').append('<link rel="stylesheet" href="style2.css" type="text/css" />');
Edit:
For the ones that would need a js function (without external files) : https://jsfiddle/t0akchuw/
You can use the load event
$('<link />', {
rel: 'stylesheet',
ref: 'https://cdnjs.cloudflare./ajax/libs/twitter-bootstrap/3.3.4/css/bootstrap.css',
type: 'text/css',
onload: function() {
snippet.log('loaded')
}
}).appendTo('head')
<script src="https://ajax.googleapis./ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- Provides the `snippet` object, see http://meta.stackexchange./a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
Another syntax
$('head').append('<link rel="stylesheet" href="https://cdnjs.cloudflare./ajax/libs/font-awesome/4.3.0/css/font-awesome.css" type="text/css" onload="dosomething()" />');
function dosomething(){
alert('d')
}
本文标签: javascriptjQuery Append CSS File and Wait until styles are applied without setIntervalStack Overflow
版权声明:本文标题:javascript - jQuery Append CSS File and Wait until styles are applied without setInterval? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742421417a2471731.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论