Detecting Broken CSS “background-images” in JavaScript/jQuery

依然范特西╮ 提交于 2019-12-22 08:06:23

问题


Here is an example to detect broken Images
http://maisonbisson.com/blog/post/12150/detecting-broken-images-in-javascript/

but is it possible to detect an broken background-image?
For exmaple:

<div style="background-image:url('http://myimage.de/image.png');"></div>

回答1:


Do you have control over the "404 not found" page on your server? In that case you could point it to a script that looks for .jpg/.png/.gif in the requested URL and log accordingly, then outputting a 404 page to the user.




回答2:


I dont think you need to have jQuery or javascript to tell you whether a link is broken. Use Firebug in Firefox and it will sort out most of your problems:

https://addons.mozilla.org/en-us/firefox/addon/firebug/

Edit: Now that I know that it was for an auto fix, i quickly had a look at it and came up with this:

var imageURLs = $('div');
imageURLs.each(function(index, element){
    var imageURL = $(element).css('background-image').replace('url("', '').replace('")', '');
    if (imageURL != "none"){
        $.ajax({
           url: imageURL,
           type: 'HEAD',
           error: function(){
              //error handling for broken image url
           }
        });
    }
});

Add that to your page after it has loaded and it will scan all div elements for any broken css background images. There might be a better or quicker way to do this but this is the general idea.

Edit 2: I noticed when i tested the script that .css('background-image') returns a string with "url()" enclosing the image url. This resulted in the ajax call failing on all urls. I changed it and actioned ajax calls on only elements which has css backgrounds. The above code now works perfect! :D



来源:https://stackoverflow.com/questions/13008150/detecting-broken-css-background-images-in-javascript-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!