Suppressing 404s in retina.js library

2019-03-12 09:12发布

We use the js lib retina.js which swaps low quality images with "retina" images (size times 2). The problem is, that retina.js throws a 404 for every "retina" image which can't be found.

We own a site where users can upload their own pictures which are most likely not in a retina resolution.

Is there no way to prevent the js from throwing 404s?

If you don't know the lib. Here is the code throwing the 404:

http = new XMLHttpRequest;
http.open('HEAD', this.at_2x_path);
http.onreadystatechange = function() {
    if (http.readyState != 4) {
        return callback(false);
    }

    if (http.status >= 200 && http.status <= 399) {
        if (config.check_mime_type) {
            var type = http.getResponseHeader('Content-Type');
            if (type == null || !type.match(/^image/i)) {
                return callback(false);
            }
        }

        RetinaImagePath.confirmed_paths.push(that.at_2x_path);
        return callback(true);
    } else {
        return callback(false);
    }
}
http.send();

7条回答
\"骚年 ilove
2楼-- · 2019-03-12 09:38

I prefer a little more control over which images are replaced.

For all images that I've created a @2x for, I changed the original image name to include @1x. (* See note below.) I changed retina.js slightly, so that it only looks at [name]@1x.[ext] images.

I replaced the following line in retina-1.1.0.js:

retinaImages.push(new RetinaImage(image));

With the following lines:

 if(image.src.match(/@1x\.\w{3}$/)) {
    image.src = image.src.replace(/@1x(\.\w{3})$/,"$1");
    retinaImages.push(new RetinaImage(image));
}

This makes it so that retina.js only replaces @1x named images with @2x named images.

(* Note: In exploring this, it seems that Safari and Chrome automatically replace @1x images with @2x images, even without retina.js installed. I'm too lazy to track this down, but I'd imagine it's a feature with the latest webkit browsers. As it is, retina.js and the above changes to it are necessary for cross-browser support.)

查看更多
登录 后发表回答