Skip to content

Instantly share code, notes, and snippets.

@jede
Created February 26, 2015 16:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jede/5fc86572344fc9f3f0b6 to your computer and use it in GitHub Desktop.
Save jede/5fc86572344fc9f3f0b6 to your computer and use it in GitHub Desktop.
Preload images in a semi fancy way
$( function () {
$( '[data-image]' ).each( function ( i, elem ) {
var $elem = $( elem ),
url = $elem.attr( 'data-image' );
if ( url == null || url.length <= 0 ) { return; }
if ( !Modernizr.svg ) {
url = url.replace( /\.svg$/, '.png' );
}
$elem.addClass( 'image-loading' );
$( '<img/>' ).attr( 'src', url ).load( function () {
$( this ).remove();
$elem.css( 'background-image', 'url(' + url + ')' );
$elem.removeClass( 'image-loading' );
$elem.addClass( 'image-ready' );
} );
} );
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment