4

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 ?

Kaiido
  • 123,334
  • 13
  • 219
  • 285
ThuyNguyen
  • 1,127
  • 3
  • 14
  • 24
  • http://stackoverflow.com/a/8767297/3344111 or http://stackoverflow.com/a/26169508/3344111 – Tahir Ahmed Aug 19 '15 at 02:50
  • 3
    possible duplicate of [jQuery Append CSS File and Wait until Loaded?](http://stackoverflow.com/questions/8767212/jquery-append-css-file-and-wait-until-loaded) – bestprogrammerintheworld Aug 19 '15 at 04: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 Aug 19 '15 at 07:21

2 Answers2

7

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

Edit:
For the ones that would need a js function (without external files) : https://jsfiddle.net/t0akchuw/

Kaiido
  • 123,334
  • 13
  • 219
  • 285
  • Hi @Kaiido, I have a question, If in 0.1s the css file can not apply, the transitionend will not be firing. And I can not make sure time to load css file? – ThuyNguyen Aug 20 '15 at 02:07
  • I think that transitions are calculated last, can't be sure though but I think it shouldn't occur, does it? – Kaiido Aug 20 '15 at 02:11
  • Good one! There's a minor typo I wanted to correct ('transtionend' to 'transitionend') but I can't because it's a change of less than 6 chars. – Tobias Beuving Apr 22 '16 at 10:29
2

You can use the load event

$('<link />', {
  rel: 'stylesheet',
  ref: 'https://cdnjs.cloudflare.com/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.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/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.com/ajax/libs/font-awesome/4.3.0/css/font-awesome.css" type="text/css" onload="dosomething()" />');

function dosomething(){
    alert('d')
}
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531