Skip to content

Instantly share code, notes, and snippets.

@philcon93
Created October 12, 2017 01:48
Show Gist options
  • Save philcon93/5495ed8aeb2a5d73792035d52ba5ef24 to your computer and use it in GitHub Desktop.
Save philcon93/5495ed8aeb2a5d73792035d52ba5ef24 to your computer and use it in GitHub Desktop.
Defer images with js

Defer images

JS

Defer images to load after page load and ensure images only for mobile or only for desktop do no load on the incorrect viewpoint.

function updateImgs() {
var imgDefer = document.getElementsByTagName('img');
for (var i=0; i<imgDefer.length; i++) {
var thisImg = imgDefer[i];
if(thisImg.getAttribute('data-src')) {
if($(thisImg).hasClass('visible-xs')){
if($(window).innerWidth() <= 767){
thisImg.setAttribute('src',thisImg.getAttribute('data-src'));
}
}else if($(thisImg).hasClass('hidden-xs')){
if($(window).innerWidth() >= 768){
thisImg.setAttribute('src',thisImg.getAttribute('data-src'));
}
}else{
thisImg.setAttribute('src',thisImg.getAttribute('data-src'));
}
}
}
}
updateImgs();
$(window).on('resize', function(){
updateImgs();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment