Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

load image asynchronous

If I have an image tag like the following:

<img src="myimage.jpg" /> 

and if I add "async" to it:

<img async src="myimage.jpg" /> 

will the image load asynchronous?

like image 890
amateur Avatar asked Apr 14 '13 13:04

amateur


People also ask

How do you load asynchronous images?

For async loading to work, either load it in JavaScript and use the onload, or include the image tag on the page, without the src attribute (specify the width and height in HTML), and go back at some point, in JS, and set the image URL.

What is image async?

A view that asynchronously loads and displays an image.

Should I lazy load images?

You should always use lazy loading for the images below the fold. As we explained, lazy loading will reduce the real and perceived loading time. User experience will benefit from it — and you users will thank you.


1 Answers

The way to async load (lazy load) the content is to not set the 'src' attribute and then execute a script that loads the images once DOM-ready is launched.

 <img data-lazysrc='http://www.amazingjokes.com/images/20140902-amazingjokes-title.png'/> 

and with jQuery (or possible with plain JavaScript too) use below code (as suggested here):

<script>   function ReLoadImages(){     $('img[data-lazysrc]').each( function(){         //* set the img src from data-src         $( this ).attr( 'src', $( this ).attr( 'data-lazysrc' ) );         }     ); }  document.addEventListener('readystatechange', event => {     if (event.target.readyState === "interactive") {  //or at "complete" if you want it to execute in the most last state of window.         ReLoadImages();     } }); </script> 
like image 121
patrick Avatar answered Sep 22 '22 05:09

patrick