Skip to content

Instantly share code, notes, and snippets.

@joho
Created June 13, 2013 05:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joho/5771506 to your computer and use it in GitHub Desktop.
Save joho/5771506 to your computer and use it in GitHub Desktop.
A CodePen by John Barton. Lazy Image Loading for Responsive Design with MetaQuery - If you're doing a responsive site that dynamically loads in extra images, this might be a neater way of doing it in a low latency way
<div class="row">
<h2>Both Images Loaded Immediately</h2>
<div class="col">
<a href="#">
<img src="http://lorempixel.com/500/500/" />
</a>
</div>
<div class="col">
<a href="#">
<img src="http://lorempixel.com/500/500/?b=2" />
</a>
</div>
</div>
<div class="row">
<h2>Images Loaded only if visible</h2>
<h3>Watch the network tab in dev tools while going from < 1000px viewport up</h3>
<div class="col">
<a href="#" class="lazy-image-container">
<noscript>
<img src="http://lorempixel.com/500/500/?b=3" />
</noscript>
</a>
</div>
<div class="col">
<a href="#" class="lazy-image-container">
<noscript>
<img src="http://lorempixel.com/500/500/?b=4" />
</noscript>
</a>
</div>
</div>
// LAZY IMAGE LOADING FOR RESPONSIVE
var lazyImageLoad = function () {
$('.lazy-image-container').each(function (index) {
var thisElement,
noScriptElement,
imgElement;
thisElement = $(this);
if (!thisElement.parent().is(':hidden')) {
noScriptElement = thisElement.find("noscript");
if (noScriptElement.size() > 0) {
thisElement.append(noScriptElement.text());
noScriptElement.remove();
}
thisElement.removeClass("lazy-image-container");
}
});
}
// fire once on page load. no need to wait for domReady because we
// load this script at the end of the page
lazyImageLoad();
// register the function to run every time a new breakpoint matches
// on a media query. the timeout is important as you need to wait
// for a browser repaint to check visibility of elements.
if (typeof(metaQuery) !== 'undefined') {
metaQuery.onBreakpointChange(function () {
setTimeout(lazyImageLoad, 0);
});
}
.breakpoint-one-image .row {
width: 500px;
}
.breakpoint-two-images .row {
width: 1000px;
}
.col {
width: 500px;
float: left;
}
.breakpoint-one-image .row .col:nth-child(even) {
display: none;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment