Tatsumi
2/21/2018 - 12:00 PM

LazyLoad

Handle lazyloading the simple way by just replacing src with data-lazy or by screen size. Simply add .lazyLoad and data-lazy with the src to get an image swithed when loaded.

For responsive images add .lazyLoadResponsive with following data attributes with a src: data-size-xl, data-size-lg, data-size-md, data-size-sm.

/*
 Project: ffm-main-template.
 Description: Handle lazyloading the simple way by just replacing src with data-lazy or by screen size.
 Simply add .lazyLoad and data-lazy with the src to get an image swithed when loaded.
 For responsive images add .lazyLoadResponsive with following data attributes:
 data-size-xl, data-size-lg, data-size-md, data-size-sm.
 Author: Tatsumi Suzuki
 Date: 2017-02-17
 Licence: https://fastforwardmedia.se
 */
"use strict";

var $ = jQuery;
var sm = 768;
var md = 1024;
var lg = 1280;

function LazyLoad() {

	var self = this;

	$('.preload').each(function() {
		self.replaceImage($(this));
	});


	$(document).ready(function() {
		self.lazyLoad();
		self.lazyLoadResponsive();
	});

	$(window).on('resize', function() {
		self.lazyLoadResponsive();
	});
}

LazyLoad.prototype.lazyLoad = function() {

	$('.lazyLoad').each(function() {
		$(this).attr('src', $(this).attr('data-lazy'));
	});
};

LazyLoad.prototype.lazyLoadResponsive = function() {
	var self = this;

	$('.lazyLoadResponsive').each(function() {
		self.replaceImage($(this));
	});
};

LazyLoad.prototype.replaceImage = function($this) {

	var winWidth = window.innerWidth;

	if(winWidth <= sm) {
		$this.attr('src', $this.attr('data-size-sm'));
	}
	else if(winWidth > sm && winWidth <= md) {
		$this.attr('src', $this.attr('data-size-md'));
	}
	else if(winWidth > md && winWidth <= lg) {
		$this.attr('src', $this.attr('data-size-lg'));
	}
	else {
		$this.attr('src', $this.attr('data-size-xl'));
	}
}