Created
September 21, 2016 21:23
-
-
Save bpb54321/7ce005fcd435ecb0149fcb62c5a44667 to your computer and use it in GitHub Desktop.
Working in tandem with create_deferred_img_tag.php, takes data from data-srcset and data-sizes of <img> elements and assigns them to the real srcset and sizes after the page has loaded lightweight images initially.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * Given a jQuery selector string corresponding to a collection of images, moves the values from the image attributes | |
| * data-srcset and data-sizes to srcset and sizes, thus loading the appropriate images in a deferred manner. Requires | |
| * jQuery. | |
| * @param String selector A String used as a jQuery selector for a collection of images. | |
| * @param startIndex The start index of the subset of the images you want to load from the collection returned from the | |
| * selector string. | |
| * @param endIndex The end index of the subset of the images you want to load from the collection returned from the | |
| * selector string. Put the same value for startIndex and endIndex if you only want a single image to be loaded. | |
| * If not supplied, will be calculated as the last index in the collection. | |
| */ | |
| function loadDeferredImages( selector, startIndex, endIndex ) { | |
| var $deferredImages = jQuery( selector ); | |
| if ( endIndex == undefined ) { | |
| endIndex = $deferredImages.length - 1; | |
| } | |
| if ( $deferredImages.length > 0 ) { | |
| for ( var i = startIndex; i <= endIndex; i++ ) { | |
| if ( i < $deferredImages.length && i >= 0 ) { | |
| if ( $deferredImages[ i ].getAttribute( 'data-srcset' ) ) { | |
| $deferredImages[ i ].setAttribute( 'srcset', $deferredImages[ i ].getAttribute( 'data-srcset' ) ); | |
| } | |
| if ( $deferredImages[ i ].getAttribute( 'data-sizes' ) ) { | |
| $deferredImages[ i ].setAttribute( 'sizes', $deferredImages[ i ].getAttribute( 'data-sizes' ) ); | |
| } | |
| } | |
| } | |
| } else { | |
| return; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment