Jump to content

Lazy Load на ванильном JavaScript

Sign in to follow this  
ArtemPitov

1,467 views

JS

class APLazy 
{
	constructor (lazyClass) 
	{
		if (typeof lazyClass === 'undefined') {
			this.lazyClass  = 'APLazy';
		} else {
			this.lazyClass  = lazyClass;
		}

		this.lazyArray = [];	
	}

	setLazy() 
	{
		this.lazyArray = document.getElementsByClassName(this.lazyClass);
	}

	cleanLazy() 
	{
		this.lazyArray = Array.prototype.filter.call(this.lazyArray, (l) => l.getAttribute('data-src'));
	}

	lazyLoad() 
	{
		for (let element of this.lazyArray) {
			if (this.isInViewport(element)) {
				if (element.getAttribute('data-src')) {
					element.src = element.getAttribute('data-src');
					element.removeAttribute('data-src');
				}
			}
		}

		this.cleanLazy();
	}

	isInViewport(element) 
	{
		var rect = element.getBoundingClientRect();

		return (
			rect.bottom >= 0 && rect.right >= 0 &&
			rect.top <= (window.innerHeight || document.documentElement.clientHeight) &&
			rect.left <= (window.innerWidth || document.documentElement.clientWidth)
		);
	}

	registerListener(event, func) 
	{
		if (window.addEventListener) {
			window.addEventListener(event, func);
		} else {
			window.attachEvent('on' + event, func);
		}
	}
}

 

Используем JS

if (typeof window.APLazy == 'undefined') {
	window.APLazy = new APLlazy('my-lazy-class');

	window.APLazy.setLazy();
	window.APLazy.lazyLoad();
			
	window.APLazy.registerListener('scroll', function () { window.APLazy.lazyLoad(); });
	window.APLazy.registerListener('resize', function () { window.APLazy.lazyLoad(); });
} else if (typeof window.APLazy == 'object' ) {
	window.APLazy.setLazy();
	window.APLazy.lazyLoad();
}

 

Используем HTML 

<img src="loader.gif" data-src="image.jpg" class="APLazy" />

 

Sign in to follow this  


0 Comments


Recommended Comments

There are no comments to display.

Guest
You are posting as a guest. If you have an account, please sign in.
Add a comment...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Recently Browsing   0 members

    No registered users viewing this page.

×

Important Information

On our site, cookies are used and personal data is processed to improve the user interface. To find out what and what personal data we are processing, please go to the link. If you click "I agree," it means that you understand and accept all the conditions specified in this Privacy Notice.