Skip to content

Instantly share code, notes, and snippets.

Last active December 25, 2015 11:58
What would you like to do?
// loadDesktopImages is looking for spans with a data-img-src attribute, whose parent is visible
// Any parent visible with CSS will trigger the replacement of the span with an image tag
// We use gridset m-hide on images we want to hide from small devices
// <noscript> is there as a backup
<div class="m-hide">
<span title="" class="media__image" data-img-src="" style=""></span>
<noscript><img title="" alt="" class="media__image" src="" style=""></noscript>
Conditionally load images for desktop view
var loadDesktopImages = function() {
$('[data-img-src]').each(function() {
if (!$(this).parent().is(':visible')) return;
var $this = $(this),
$imgClass = $this.attr('class'),
$imgStyle = $this.attr('style'),
$imgTitle = $this.attr('title'),
$imgSrc = $'img-src'),
// Create image element
$img = $('<img />')
.attr('style', $imgStyle)
.attr('title', $imgTitle)
.attr('alt', $imgTitle)
.attr('src', $imgSrc)
// Add class to parent so we can apply CSS
// Inject img into DOM in place of span
// add resize handler to capture rotation/resize changes
// requires
$(window).resize($.debounce(loadDesktopImages, 1000));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment