I’m running a Javascript replace function to replace standard images with class="replace-2x"on my jQuery Mobile site with Retina-quality images if the user is on a mobile device with Retina display. For example, on a Retina device, logo.png will be replaced with logo@2x.png. The JS function is here:
function highdpi_init() {
$(".replace-2x").each(function () {
var src = $(this).attr("src");
$(this).attr("src", src.replace(".png", "@2x.png").replace(".jpg", "@2x.jpg"));
});
}
$(".page").live('pageinit',function(event){
highdpi_init();
});
I’m now running into an issue where the replace function is running more than once. So for example, it replaces logo.png with logo@2x.png as the page is loading, but then as the page continues to load, it KEEPS replacing .png with @2x.png in the img src over and over so that the image tag ends up looking like this:
<img src="mobile/images/logo@2x@2x@2x@2x@2x@2x@2x@2x@2x@2x@2x.png" class="replace-2x" alt="logo" width="200">
How can I prevent this from replacing on a single img element more than once? Keep in mind, I will have multiple images on the same page, so the function will need to apply to all images, but only one time each.
The problem is surely that your ‘pageinit’ event is being called more than once. You can either follow MДΓΓ БДLL’s idea (which won’t work if images are dynamically added) or you can make your handler smarter so that it doesn’t replace the src if it already was replaced
You don’t need JS for this, you could do it in CSS only.
You could make your images look like
And in
highdpi.cssyou could doAnd in
lowdpi.css