How to determine if a linked resource has been successfully loaded

I use the following JavaScript to dynamically load style sheets:

function set_stylesheet(name) { var link = document.getElementById('userstylelink'); link.href = link.href.replace(/[^\/]+\.css$/, name + '.css'); } 

Can I determine if a new CSS file is uploaded? If this fails, I would like to apply the default stylesheet.

+6
source share
5 answers

You might want to see my answer to another similar question: Detection and registration when it is not possible to load external JavaScript or CSS resources

Basically, you can add an onload callback to see if the file is uploaded. (If you download via JS, of course)

+1
source

The easiest way is to check the styleSheet.cssText property of the link element after assigning a new href.

 function set_stylesheet(name) { var link = document.getElementById('userstylelink'); link.href = link.href.replace(/[^\/]+\.css$/, name + '.css'); if ( link.styleSheet.cssText ) { //if not empty string, it was loaded } else { link.href = "default.css"; } 

Alternatively, there is an onerror event that fires when a resource cannot load after href is assigned.

+1
source

Ideally, you should load them all at the beginning and then switch between them.

http://www.alistapart.com/articles/alternate/

http://www.thesitewizard.com/javascripts/change-style-sheets.shtml

This does not really answer the question, but I think this method is preferable.

0
source

I would recommend loading via ajax, checking the response as the pimvbd user mentions, but also puts a dummy rule at the end of your stylesheet, which erases the hidden element with the declaration that you can check. For example, give a hidden border div: 987px and check if the hidden border div is actually 987px. Yes, it introduces a dependency on this style and this element. I have had endless discussions about this with many people, and there is no better way (yet). We hope that in the near future you will get some attention in browser releases ...

0
source

There is a solution that does not require javascript or style sheet loading detection.

It seems you can also apply a default style with a built-in style sheet, and then override the default values ​​with the dynamically loaded style sheet. If the new stylesheet does not load, the default value is already loaded and in place, nothing else needs to be done. If a new stylesheet is loaded, it simply overrides the default values ​​and shows the new style.

0
source

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


All Articles