开发者

How to determine whether a linked resource loads successfully

开发者 https://www.devze.com 2023-02-23 13:42 出处:网络
I\'m using the following JavaScript to dynamically load stylesheets: function set_stylesheet(name) { var link = document.getElementById(\'userstylelink\');

I'm using the following JavaScript to dynamically load stylesheets:

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

Is there any way to determine whether the new CSS file is loaded successfully? If it fails, I'd like t开发者_运维问答o be able to apply a default stylesheet.


You might want to see my answer to another similar question here: Detect and log when external JavaScript or CSS resources fail to load

Basically, you can add an onload callback to see if the file was loaded. (If you load via JS of course)


The simplest way is to check styleSheet.cssText property of the link element after a new href was assigned.

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 "onerror" event which fires when the resource fails to load after href assigned.


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

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

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

That doesn't really answer the question, but I think this way is preferred.


I'd recommend loading via ajax, checking the response as the user pimvbd mentions, but also place a dummy rule at the end of your stylesheet that styles a hidden element with a declaration you can check. For example, give a hidden div border: 987px and check to see if the hidden div's border is in fact 987px. Yes, it introduces a dependency on that style and that element. I've had endless discussions on this with many people, and there's not really a better way (yet). Hopefully s get some attention in browser releases in the near future...


There is a solution that requires no javascript or detection of whether the stylesheet loaded.

It seems you could also apply your default style with a built-in style sheet and then have the dynamically loaded stylesheet override the defaults. If the new stylesheet doesn't load, the default is already loaded and in place, nothing further to do. If the new stylesheet does load, it just overrides the default values and shows the new style.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号