Patartics Milán
Patartics Milán

Reputation: 4938

Set image src with jquery on load

I am working on a website that has image blocks, with various sizes (relative width based on the current size of the parent, parent also have a relative size to window). I use jquery load event to rewrite the src attributes of the images based on the image object's dynamic size to ensure pixel perfect view. The problem is that the browser download the full size image, than replace it with a dynamically generated one. This leads to unnecessary loadings and speed loss.

What if I let the src value empty, that add the correct url into it? I would like to stay seo optimized, so an empty src maybe not a good idea. Can I achieve this without double downloading images? Maybe I should use an event before the browser begins the download the src data.

My code:

$('.image').load(function () {
    if (!$(this).hasClass('optimized')) {
        $(this).attr('src', '/image-perfection.php?image=' + encodeURIComponent($(this).attr('src')) + '&width=' + $(this).width());
        $(this).addClass('optimized');
    }
});

Upvotes: 0

Views: 191

Answers (1)

Edgar Alexander
Edgar Alexander

Reputation: 374

Create a small thumbnail, and let your images to point to the same thumbnail image.

The advantage of this is that you can specify a 'loading' like image that will be pre-catched by the browser for next requests, and then you can load the images the way you do.

You can also write a proxy script that cut the images in the server for you, if you're working with uploaded images you can cut them once they're uploaded for optimize the process, of course it depends of how your implementation must be.

Upvotes: 1

Related Questions