0

I am looking for a way to scale images of a web page for mobile devices. My approach is to store the dimensions of each image using JavaScript, and if the screen of the user is smaller than a certain value, all images will be resized using JavaScript. My problem is that the following function does not detect if the images are already loaded, so the result would be 0 for not loaded images. My question is, how can I implement a check, so that the function will compute the image size only after the image was completely loaded? I am not using jQuery.

function storeImageSizes() {
  isizes = [];
  imgs = document.getElementById('content').getElementsByTagName('img');
  for (var i = 0; i < imgs.length; i++) {
    isizes[i] = [
      window.getComputedStyle(imgs[i]).getPropertyValue('width').replace('px', '') * 1,
      window.getComputedStyle(imgs[i]).getPropertyValue('height').replace('px', '') * 1
    ];
  }
}
Luca Kiebel
  • 9,790
  • 7
  • 29
  • 44
atarax42
  • 13
  • 8
  • this will help https://stackoverflow.com/questions/544993/official-way-to-ask-jquery-wait-for-all-images-to-load-before-executing-somethin – Hitesh Kansagara Sep 14 '18 at 18:41

4 Answers4

0

Add a listener to be called when all DOM elements load. ie:

document.addEventListener("load", (function(){
   isizes = [];
  imgs = document.getElementById('content').getElementsByTagName('img');
  for (var i = 0; i < imgs.length; i++) {
    isizes[i] = [
      window.getComputedStyle(imgs[i]).getPropertyValue('width').replace('px', '') * 1,
      window.getComputedStyle(imgs[i]).getPropertyValue('height').replace('px', '') * 1
    ];
  }
})
michaelitoh
  • 2,317
  • 14
  • 26
  • I used `window.addEventListener()` instead of `document.addEventListener()` and this worked for me. Thanks! – atarax42 Sep 15 '18 at 07:44
0

Calling storeImageSizes() in window.load function should fix the problem

$( window ).on( "load", function() { ... })

It basically is an event which is triggered when all the images and the complete page is loaded. Since you want the function to run when all the images are loaded you should use this event.

Note the difference between document.ready and window.load. document.ready runs when the DOM is ready where as window.load runs once the complete page is loaded i.e., images/iframes etc.

Take reference from here Simple example using Jquery

d_bhatnagar
  • 1,419
  • 1
  • 12
  • 20
0

You can use the following solution to perform image analysis after the images are already loaded:

document.querySelector('#image').addEventListener('load', storeImageSizes);
Grant Miller
  • 27,532
  • 16
  • 147
  • 165
Arek C.
  • 1,271
  • 2
  • 9
  • 17
0

Did you try image.onload?
Also, check this answer out. It highlights the use of image.onload and also avoids browser cache issues.