Search code examples
jquery-mobilemedia-queriesretina-displayimage-replacement

jQuery Mobile - CSS Retina Image Replacement


I have a mobile site running with jQuery Mobile. I want to have standard images for non-retina (devices without a high pixel density) devices, but want those images replaced with retina (high pixel density) images that are 2x the size of the original when viewed on a high pixel density device. I found this article here: http://flowz.com/2010/07/css-image-replacement-for-iphone-4-high-dpi-retina-display/

My jQuery for the implementation looks for images with class="replace-2x", and replaces the standard image with one at the same path with @2x added to the file name. So logo.png would be replaced with [email protected] on a Retina device. My jQuery looks like this:

function highdpi_init() {
    if(jQuery('.replace-2x').css('font-size') == "1px") {
        var els = jQuery(".replace-2x").get();
        for(var i = 0; i < els.length; i++) {
            var src = els[i].src
            src = src.replace(".png", "@2x.png");
            els[i].src = src;
        }
    }
}
jQuery(document).ready(function() {
    highdpi_init();
});

When the page loads however, this function is not being called or working (one or the other) so I'm not sure if I need something like $(".page").live('pageinit', function() { instead or what so that the function fires or "works" when the page loads? Help?? :)


Solution

  • In JQuery mobile, you need to use the pageinit, because the ready function is only called once; every other page is loaded via Ajax, which won't trigger a ready event. See JQuery Mobile Events for more information.

    function highdpi_init() {
        $(".replace-2x").each(function () {
            if ($(this).css("font-size") == "1px") {           
                var src = $(this).attr("src");
                $(this).attr("src", src.replace(/(@2x)*.png/i, "@2x.png").replace(/(@2x)*.jpg/i, "@2x.jpg"));
                $(this).removeClass('replace-2x')
            }
    });
    
    $(".ui-page").live('pageinit',function(event){
        highdpi_init();
    });