Main Content

A better way to preload images

The standard way to preload images is to use lazy this will reveal the images when user is in viewport but the problem is that when you have 20 images in that viewport this will load parallel. Parallel downloading splits the bandwidth depends on how many images that are being download this can be done using t his method AI Lazy Load. This how parallel preloading work:

While sequential preloading will download image one after another this has a full bandwidth itself and is ready almos 1-2 seconds and 500% faster than the parallel preloading. One concern for this method is that this need to fire on page load only. This graph will show how suquential preloading works:

HTML

<img src="images/clear.png" data-seq-src="images/sample-image.png">

JavaScript

( function( $ ){

	$( document ).ready( function() {
		var $data_src 	= $( '[data-seq-src]' ),
			imgArr 		= [],
			_count 		= 0;

		$data_src.each( function() {
			var $this 	= $(this),
				_img 	= $this.attr('data-seq-src');

			if ( _img != '' ) {
				$this.attr( 'data-seq-src-index', _count );
				imgArr[_count] = _img;
				_count++;
			}
		} );

		$( window ).on( 'load', function() {
			function sequential_requests( imageArray, index ) {
				index = index || 0;

				if (imageArray && imageArray.length > index) {
					image_temp 			= new Image();
					image_temp.src 		= imageArray[index];
					image_temp.onload 	= function() {
						sequential_requests(imageArray, index + 1);

						$elem = $( '[data-seq-src-index=' + index + ']' )
						if ( $elem.prop("nodeName") == 'IMG' ) {
							$elem.attr( 'src', imageArray[index] );
						} else if ( $elem.prop("nodeName") == 'CANVAS' || $elem.prop("nodeName") == 'DIV' ) {
							$elem.css({'background-image': 'url(' + imageArray[index] + ')'});
						}
					}
				}
			};

			sequential_requests( imgArr );
		} );

	} );

} )( jQuery );