Pure jQuery Change Image to HD Resolution
Pure jQuery Change Image to HD Resolution

awproject.net – In first of era, Apple become the first brand using screen technology named retina display. Basicly this technology using screen with 2x pixel size, so everything on screen look more sharp and smooth.

The problem is, the image file can not support this image resolution, so the image who have default resolution look blury. For tweak this case we need make image must have 2x resolution of default image and the image look sharp.

To solve this problem many things what we can do. Like we can use retina.js library. but on this post i have some alternative only using jQuery script.

The advantages of this case, we can reduce usage of javascript library, and make our site more fast. and this is not only run on apple device but also on android device. please follow this step by step.

1. Make sure on your site directory have 2 file image. The first thumbnail.png as default image has resolution 150 x 150px. and the scond file are thumbnail@2x.png

2. Load jQuery script library. Place on footer before </body> tag

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

3. and this is jQuery Script to chane image URL to HD url sourch.

// Check if load on HD Screen
var query = "(-webkit-min-device-pixel-ratio: 2), (min-device-pixel-ratio: 2), (min-resolution: 192dpi)";

  if (matchMedia(query).matches) {
    // If HD Screen
    // Get default image URL
    var default_image = $('img');
    var image_src = $(default_image).attr('src');
    
    // get file name from image url
    var src = image_src.split('/');
    var file = src[src.length - 1].split('.');
    var file_extention = file[1];

    // Update filename ie : filename@2x.png
    var hd_image = image_src.replace(file_name, file_name + '@2x');

    // Check image availability
    var image = new Image();
    image.src = hd_image;

    image.onload = function(){
      // if image available update image src to hd image sourch
      $(default_image).attr('src',hd_image);
    };
  }

Thanks for reading :mrgreen: sorry my bad english. Any Question? leave comment below.

widhy980

Blogger, Web Developer & Traveler

Hi, I am from Indonesia, and i have more interest about website development. i have good skill on Codeigniter, Wordpress, HTML x CSS and Bootstrap. have a business? please contact me ... :D

You Might Also Like

Leave a Reply

Your email address will not be published. Required fields are marked *