Dynamically load StyleSheet using callback function

I have this short JavaScript function that dynamically loads a CSS file. But I'm still not good at JavaScript, so can someone give me an idea on how to create a callback function after successfully loading the CSS file ...

function loadStyleSheet(url){ if(document.createStyleSheet) { try {document.createStyleSheet(url);} catch (e) { } } else{ var css; css = document.createElement('link'); css.rel = 'stylesheet'; css.type = 'text/css'; css.media = "all"; css.href = url; document.getElementsByTagName("head")[0].appendChild(css); } } 

PS If you have an idea, how can I find out if the CSS file failed to load. Ok, I will be grateful to you more ^ _ ^

+4
source share
4 answers

I'm not sure if there is a bulletproof way to check if a stylesheet is loaded. This depends primarily on whether CSS is loaded from the same domain.

The trick I used to check if CSS is loaded is to add (or use) a well-known rule in CSS as follows:

  • Example rule: .foobar { display: none; } .foobar { display: none; }
  • Add item to my document: <span class="foobar"></span>
  • Load CSS using the method you used
  • Interrogate the document at regular intervals with window.setTimeout() and check if span.foobar remains. When it is hidden, it means that CSS has loaded
+3
source

Pass the callback function as an argument to your function, and then call it after loading your stylesheet.

For instance:

 function myFunc() { alert("Hello, World"); } loadStyleSheet("link/to/stylesheet.css", myFunc); function loadStyleSheet(url, callback){ if(document.createStyleSheet) { try {document.createStyleSheet(url);} catch (e) { } } else{ var css; css = document.createElement('link'); css.rel = 'stylesheet'; css.type = 'text/css'; css.media = "all"; css.href = url; document.getElementsByTagName("head")[0].appendChild(css); } callback(); } 

EDIT

If you want to check if it loaded the stylesheet correctly, you will need to use AJAX .

+2
source

I think I found the answer to my problem ^ _ ^ http://yepnopejs.com/

Thank you all for your help ^ _ ^

0
source

I think the easiest way would be to add markup to the head when loading

 $('<link rel="stylesheet" href="link.css" type="text/css" />').appendTo("head") .each(function() { //little trick to create the callback function // I am the callback }); 

PS: this is a jQuery solution. I did not notice the JS and CSS tag, but still its a good solution

-2
source

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


All Articles