Created
September 27, 2021 08:28
-
-
Save aydgn/b8b5a86d92d85a6b0934f979418067ff to your computer and use it in GitHub Desktop.
Lazy Loader
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * lazyLoader | |
| * Check for elements in the document to be loaded later when visible to the user. | |
| * @see https://developers.google.com/web/fundamentals/performance/lazy-loading-guidance/images-and-video/ | |
| * @example | |
| * <element src="" data-src="/url/" data-srcset="..." /> | |
| */ | |
| (function (ready) { | |
| if (document.readyState === "complete" || document.readyState === "interactive") { | |
| ready(); | |
| } else { | |
| document.addEventListener("DOMContentLoaded", ready); | |
| } | |
| })(function lazyLoader() { /* the document is now ready. */ | |
| var lazyEls = [].slice.call(document.querySelectorAll("[data-src]")); | |
| function load(el) { | |
| var src = el.getAttribute("data-src"); | |
| var srcset = el.getAttribute("data-srcset"); | |
| if (src) { el.setAttribute("src", src); } | |
| if (srcset) { el.setAttribute("srcset", srcset); } | |
| el.removeAttribute("data-src"); | |
| el.removeAttribute("data-srcset"); | |
| } | |
| if ("IntersectionObserver" in window) { | |
| var lazyObserver = new IntersectionObserver(function(entries) { | |
| entries.forEach(function(entry) { | |
| if (entry.isIntersecting) { | |
| var el = entry.target; | |
| load(el); | |
| lazyObserver.unobserve(el); | |
| } | |
| }); | |
| }); | |
| lazyEls.forEach(function(el) { | |
| if (el.tagName === "SCRIPT") { | |
| load(el); | |
| } | |
| else { | |
| lazyObserver.observe(el); | |
| } | |
| }); | |
| } | |
| else { | |
| lazyEls.forEach(load); | |
| } | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment