I’d like to change the src attribute of images before they are requested by the browser, the aim being to reduce the size of the images using a PHP script like Timthumb. Using jQuery, I thought $(document).ready would do the trick:
$(document).ready(function () {
var imgs = $('#container img');
jQuery.each(imgs, function() {
$(this).replaceWith('<img src="timthumb/timthumb.php?src=' + $(this).attr('src') + '&w=200" />');
});
});
But the original, unresized image is still downloaded in the background to the browser’s cache. Is it possible to do what I’m trying to do on the client side, or is server-side the only option?
Javascript loading and execution is serialized by the browser (unless you use something like
head.js), but the problem is that the DOM has to be available for a script to modify it. The jQuery ready event fires after the DOM is available, so the browser has already started requesting the resources that were referenced in the HTML.So if you put the Javascript before the image tag it won’t be able to find the image tags, and once ready fires the download has already started. I’m not aware of any events that fire before image load (just one for aborts), so the cleanest method is to create the HTML with the modified
srcattributes in the first place.Alternatively, put the
srcin a different attribute on the image (likedata_orig_src) and run the script to setsrctodata_orig_srcon each image upon document ready. Use CSS to hide the images before changing thesrcso the user doesn’t see a broken image icon. I think this is probably better than adding the images after the fact because you won’t need to track where the images need to be placed in the DOM, and it should perform better as well.Of course if you can change the server to use
data_orig_srcinstead ofsrc, why not just put the propersrcin the tag in the first place…