Perform image analysis only after images are already loaded
Perform image analysis only after images are already loaded
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
];
4 Answers
4
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
];
)
I used
window.addEventListener()
instead of document.addEventListener()
and this worked for me. Thanks!– atarax42
Sep 15 '18 at 7:44
window.addEventListener()
document.addEventListener()
Did you try image.onload?
Also, check this answer out. It highlights the use of image.onload
and also avoids browser cache issues.
image.onload
You can use the following solution to perform image analysis after the images are already loaded:
document.querySelector('#image').addEventListener('load', storeImageSizes);
Calling storeImageSizes() in window.load function should fix the problem
$( window ).on( "load", function() ... )
$( 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
Thanks for contributing an answer to Stack Overflow!
But avoid …
To learn more, see our tips on writing great answers.
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
this will help stackoverflow.com/questions/544993/…
– Hitesh Kansagara
Sep 14 '18 at 18:41