且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

处理破碎图像的***方式是什么?

更新时间:2022-10-15 23:33:56

一个想到的事情是在你的web服务器上创建一个图像处理程序,例如

 < img src =fetchimage.aspx?name = test.jpgalt =testtitle =test/> 

忽略aspx,很显然它会被您首选的服务器脚本技术取代。然后,处理程序可以通过为所有未知图像名称提供missing.jpg来处理图像名称。

尽我所能看到。在页面加载之前运行的任何JavaScript都无法迭代尚未收到的img标记,并且任何等待页面准备就绪的脚本都将冒着用户看到破碎图像的风险。

Rock-> You< -Hardplace


So there seems to be quiet a few ways to handle broken images on a html page. I would like to know what ways are in popular use and what ways are viewed to be best practice?

To start I've looked at some myself like:

function imgErr(source) {     
    source.src = /images/missing.jpg";
    source.onerror = "";
    return true;
}
<img src="test.jpg" alt="test" title="test" onerror="imgErr(this);" />

Pros: works everytime, the event will always be caught. User never sees broken image. Seems to work well across the browsers. Cons: onerror tag required on each image, function imgErr(source) needs to be in the head to catch the errors, slows down the users experienced load time

$('img').error(function(){
  $(this).attr('src', 'missing.jpg');
});

Pros: very little code, works on all images without changing their markup, can be place outside of the head Cons: can miss the error event depending on the speed of the pages onload event, slows down the users experienced load time

$(window).load(function() {
    $("img").each(function() {
        if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) {
            var src = $(this).attr("src");
            var suffix = src.substring(src.length - 6, src.length).split('.')[0];
            suffix = suffix.charAt(suffix.length - 1);            
            $(this).attr("src", "/static/images/generic/missing_" + suffix + ".jpg");
        }
    });
});

Pros: Can be placed anywhere on the page, will fix the images no matter when it gets to run, doesn't slow down the users experienced load time Cons: shows a broken image till it runs creating a poor user experience

In my situation load time is the greatest issue but I can't get the last option to work in IE properly as it changes broken and none broken images alike!

Cheers, Denis

One thought that does spring to mind is to create an image handler at your web server, i.e.

<img src="fetchimage.aspx?name=test.jpg" alt="test" title="test" />

Ignore the aspx, obviously it'd be replaced with whatever your preferred server scripting technology was. That handler can then deal with image names that aren't present by delivering your missing.jpg for all unknown image names.

Other than that you are stuck with the options you give as far as I can see. Any javascript that runs before the page has loaded risks not iterating over img tags not yet received and any script that waits for page ready is going to risk the user seeing broken images.

Rock->You<-Hardplace