Sophia Sophia - 7 months ago 10
Javascript Question

jQuery Append CSS File and Wait until styles are applied without setInterval?

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 ?

Answer

One 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" />');