JQuery Add CSS file and wait for it to load?

I am trying to add a css file using

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

This works fine - however, I have some functions that run AFTER CSS is added, and I can't figure out how they can wait until this file finishes loading?

How can i do this?

+6
source share
2 answers

Just check when one of the rules of the new CSS was 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) 

(This is a working example)

+3
source

The first thing to do is put your functions in a ready-made method that will perform these functions after loading the DOM.

 <script type="text/javascript"> jQuery(document).ready(function() { // Your functions come here }); </script> 

Then just put the script in front of </body>. Thus, append will be launched in the same way as dom.

 <script type="text/javascript"> $('head').append(); </script> 

Another approach is to use a load event:
Check this link with a working example, inside it I set the body with a green background, it loads the stackoverflow stylesheet, which when the download is completed changes the body to white.
http://jsfiddle.net/CQbqA/1/

-1
source

Source: https://habr.com/ru/post/905379/


All Articles