Repository: ApoorvSaxena/lozad.js Branch: master Commit: e9cd983b37c6 Files: 21 Total size: 105.8 KB Directory structure: gitextract_jo9cucp3/ ├── .editorconfig ├── .github/ │ └── issue_template.md ├── .gitignore ├── .travis.yml ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── bower.json ├── demo/ │ ├── assets/ │ │ ├── css/ │ │ │ ├── ie8.css │ │ │ ├── ie9.css │ │ │ └── main.css │ │ └── js/ │ │ ├── ie/ │ │ │ └── html5shiv.js │ │ └── main.js │ ├── index.html │ └── video/ │ └── mov_bbb.ogg.ogv ├── dist/ │ ├── lozad.es.js │ └── lozad.js ├── package.json ├── rollup.config.js ├── src/ │ └── lozad.js └── test/ └── index.js ================================================ FILE CONTENTS ================================================ ================================================ FILE: .editorconfig ================================================ # This file is for unifying the coding style for different editors and IDEs # editorconfig.org root = true [*] charset = utf-8 end_of_line = lf insert_final_newline = true trim_trailing_whitespace = true [*.{html}] indent_style = space indent_size = 4 [*.{js, json, yml, css, md}] indent_style = space indent_size = 2 ================================================ FILE: .github/issue_template.md ================================================ Your issue may already be reported! Please search on the [issue track](../) before creating one. ## Expected Behavior ## Current Behavior ## Possible Solution ## Steps to Reproduce (for bugs) 1. 2. 3. ## Context ## Tested on: * Browser Name and version: * Operating System and version (desktop or mobile): ================================================ FILE: .gitignore ================================================ node_modules .nyc_output .idea .DS_Store thumbs.db *.log* coverage ================================================ FILE: .travis.yml ================================================ sudo: false language: node_js node_js: - '8' script: - rm -rf node_modules - npm install - npm run build - npm run test deploy: provider: npm email: $NPM_EMAIL api_key: $NPM_API_KEY on: tags: true # make sure we keep our dist directory skip_cleanup: true ================================================ FILE: CONTRIBUTING.md ================================================ # Contributing to lozad.js :sparkles:First off, thanks for taking the time to contribute!:sparkles: Now, take a moment to be sure your contributions make sense to everyone else. These are just guidelines, not rules. Use your best judgment, and feel free to propose changes to this document in a pull request. ## How can I contribute? ### Using Lozad.js? Share with us, and we'll mention it on the project homepage. When adding site to the *list of sites using Lozad.js*, please mention where to verify this in the PR description. ### Improve documentation As a user of Lozad.js, you're the perfect candidate to help us improve our documentation. Typo corrections, error fixes, better explanations, more examples, etc. Open issues for things that could be improved. Anything. Even improvements to this document. ### Improve issues Some issues are created with missing information, not reproducible, or plain invalid. Help make them easier to resolve. Handling issues takes a lot of time that we could rather spend on fixing bugs and adding features. ### Give feedback on issues We're always looking for more opinions on discussions in the issue tracker. It's a good opportunity to influence the future direction of Lozad.js ## Reporting Issues - Found a problem? Want a new feature? First of all see if your issue or idea has [already been reported](https://github.com/ApoorvSaxena/lozad.js/issues). - If not, just open a [new clear and descriptive issue](https://github.com/ApoorvSaxena/lozad.js/issues/new). - Use a clear and descriptive title. - Include as much information as possible: Steps to reproduce the issue, error message, Browser version, operating system, etc. - The more time you put into an issue, the more we will. ## Submitting pull requests - Non-trivial changes are often best discussed in an issue first, to prevent you from doing unnecessary work. - For ambitious tasks, you should try to get your work in front of the community for feedback as soon as possible. Open a pull request as soon as you have done the minimum needed to demonstrate your idea. At this early stage, don't worry about making things perfect, or 100% complete. Add a [WIP] prefix to the title, and describe what you still need to do. This lets reviewers know not to nit-pick small details or point out improvements you already know you need to make. - New features should be accompanied with tests and documentation. - Don't include unrelated changes. - Lint and test before submitting the pull request. - Make the pull request from a [topic branch](https://github.com/dchelimsky/rspec/wiki/Topic-Branches), not master. - Use a clear and descriptive title for the pull request and commits. - Write a convincing description of why we should land your pull request. It's your job to convince us. Answer "why" it's needed and provide use-cases. - You might be asked to do changes to your pull request. There's never a need to open another pull request. [Just update the existing one.](https://github.com/RichardLitt/docs/blob/master/amending-a-commit-guide.md) ## Code Style Follow the [xo](https://github.com/sindresorhus/xo) style. Using two spaces for identation and no [semicolons](http://blog.izs.me/post/2353458699/an-open-letter-to-javascript-leaders-regarding). ## Commit Message Emoji Every commit is important. So let's celebrate each and every commit with a corresponding emoji! :smile: ### Which Emoji to Use? :confused: Commit Type | Emoji ---------- | ------------- Initial Commit | :tada: `:tada:` Improve the format/structure of the code | :art: `:art:` Improving performance | :racehorse: `:racehorse:` Writing docs | :memo: `:memo:` Fix a bug | :bug: `:bug:` Remove code or files | :fire: `:fire:` Fix CI build | :green_heart: `:green_heart:` Deal with security | :lock: `:lock:` Upgrade dependencies | :arrow_up: `:arrow_up:` Downgrading dependencies | :arrow_down: `:arrow_down:` Add tests | :umbrella: `:umbrella:` Improving accessibility | :wheelchair: `:wheelchair:` Add new features | :sparkles: `:sparkles:` Refactoring | :package: `:package:` Other | [Be creative](http://www.emoji-cheat-sheet.com/) ## Scripts The follow scripts are available when you develop. - `npm run lint` - Lint the files. - `npm run build` - Build the package. - `npm run test` - Test. ================================================ FILE: LICENSE ================================================ The MIT License (MIT) Copyright (c) 2017 Apoorv Saxena Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: README.md ================================================ # Lozad.js [![npm version](https://badge.fury.io/js/lozad.svg)](https://badge.fury.io/js/lozad) [![Build Status](https://travis-ci.org/ApoorvSaxena/lozad.js.svg?branch=master)](https://travis-ci.org/ApoorvSaxena/lozad.js) [![npm](https://img.shields.io/npm/dm/lozad)](https://www.npmjs.com/package/lozad) [![](https://data.jsdelivr.com/v1/package/npm/lozad/badge)](https://www.jsdelivr.com/package/npm/lozad) > Highly performant, light and configurable lazy loader in pure JS with no dependencies for images, iframes and more, using IntersectionObserver API ![lozad.js lazy loading javascript library](./banner/lozad-banner.jpg "lozad.js lazy loading javascript library") **Lozad.js**: - lazy loads elements performantly using pure JavaScript, - is a light-weight library, just [![](http://img.badgesize.io/https://cdn.jsdelivr.net/npm/lozad?compression=gzip)](https://cdn.jsdelivr.net/npm/lozad) minified & gzipped, - has NO DEPENDENCIES :) - allows lazy loading of dynamically added elements as well, - supports <img>, <picture>, iframes, videos, audios, responsive images, background images and multiple background images etc. - even supports LQIP (Low Quality Image Placeholder) - is completely free and open source. - it will reload when the valid attributes change. It is written with an aim to lazy load images, iframes, ads, videos or any other element using the recently added [Intersection Observer API](https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API) and [MutationObserver](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver) with tremendous performance benefits. ## Featured in: - [Web | Google Developers](https://developers.google.com/web/fundamentals/performance/lazy-loading-guidance/images-and-video/) - [Product Hunt](https://www.producthunt.com/posts/lozad-js) - [Reddit](https://www.reddit.com/r/webdev/comments/6zg1x0/highly_performant_light_05kb_and_configurable/) - [CSS Tricks](https://css-tricks.com/lozad-js-performant-lazy-loading-images) - [David Walsh](https://twitter.com/davidwalshblog/status/915319510646829061) - [Codrops](https://twitter.com/Apoorv_Saxena/status/906586828265758720) - [SitePoint](https://www.sitepoint.com/five-techniques-lazy-load-images-website-performance/) ## Brands using Lozad.js: ![Tesla](./brands/tesla.png)          ![Binance](./brands/binance.png)          ![Domino's](./brands/dominos.png)          ![BNP Paribas](./brands/bnp-paribas.png)          ![Mi](./brands/xiaomi.png)          ![Amway](./brands/amway.png)          ![TATA](./brands/tata.png)          ![Verizon](./brands/verizon.svg) ![Atlassian](./brands/atlassian.svg) ![BNP Paribas](./brands/livemint.svg) ![JLM Couture](./brands/jlm-couture.png)          ![New Balance](./brands/new-balance.png)          ![BBC](./brands/bbc.png) and many more... ## Table of Contents - [Demo](https://apoorv.pro/lozad.js/demo/) - [Background](#yet-another-lazy-loading-javascript-library-why) - [Install](#install) - [Usage](#usage) - [Example with picture tag](#example-with-picture-tag) - [Browser Support](#browser-support) - [FAQs](#faqs) - [Contribute](#contribute) - [Changelog](#changelog) - [License](#license) ## Yet another Lazy Loading JavaScript library, why? Existing lazy loading libraries hook up to the scroll event or use a periodic timer and call `getBoundingClientRect()` on elements that need to be lazy loaded. This approach, however, is painfully slow as each call to `getBoundingClientRect()` forces the browser to re-layout the entire page and will introduce considerable jank to your website. Making this more efficient and performant is what [IntersectionObserver](https://developers.google.com/web/updates/2016/04/intersectionobserver) is designed for, and it’s landed in Chrome 51. IntersectionObservers let you know when an observed element enters or exits the browser’s viewport. ## Install ```sh # You can install lozad with npm $ npm install --save lozad # Alternatively you can use Yarn $ yarn add lozad # Another option is to use Bower $ bower install lozad ``` Then with a module bundler like rollup or webpack, use as you would anything else: ```javascript // using ES6 modules import lozad from 'lozad' // using CommonJS modules var lozad = require('lozad') ``` Or load via **CDN** and include in the `head` tag of your page. ```html ``` When loading from CDN, you can find the library on `window.lozad`. --- ## Usage In HTML, add an identifier to the element (default selector identified is `lozad` class): ```html ``` All you need to do now is just instantiate Lozad as follows: ```js const observer = lozad(); // lazy loads elements with default selector as '.lozad' observer.observe(); ``` or with a DOM `Element` reference: ```js const el = document.querySelector('img'); const observer = lozad(el); // passing a `NodeList` (e.g. `document.querySelectorAll()`) is also valid observer.observe(); ``` or with custom options: ```js const observer = lozad('.lozad', { rootMargin: '10px 0px', // syntax similar to that of CSS Margin threshold: 0.1, // ratio of element convergence enableAutoReload: true // it will reload the new image when validating attributes changes }); observer.observe(); ``` Reference: - [IntersectionObserver options: rootMargin](https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver/rootMargin) - [IntersectionObserver options: thresholds](https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver/thresholds) or if you want to give custom function definition to load element: ```js lozad('.lozad', { load: function(el) { console.log('loading element'); // Custom implementation to load an element // e.g. el.src = el.getAttribute('data-src'); } }); ``` If you would like to extend the `loaded` state of elements, you can add the loaded option: > **Note**: The `"data-loaded"="true"` attribute is used by lozad to determine if an element has been previously loaded. ```js lozad('.lozad', { loaded: function(el) { // Custom implementation on a loaded element el.classList.add('loaded'); } }); ``` If you want to lazy load dynamically added elements: ```js const observer = lozad(); observer.observe(); // ... code to dynamically add elements observer.observe(); // observes newly added elements as well ``` for use with responsive images ```html ``` for use with background images ```html
``` for use with multiple background images ```html
``` for use with responsive background images (image-set) ```html
``` To change the delimiter that splits background images: ```html
``` If you want to load the images before they appear: ```js const observer = lozad(); observer.observe(); const coolImage = document.querySelector('.image-to-load-first'); // ... trigger the load of a image before it appears on the viewport observer.triggerLoad(coolImage); ``` ### Large image improvment Sometimes image loading takes a long time. For this case, you can add a placeholder background: ```html ``` Lozad sets a placeholder background color of img element and users will see the fallback till the image loads. ## Example with picture tag Create _a broken_ picture element structure. > IE browser don't support picture tag! > You need to set `data-iesrc` attribute (only for your picture tags) with source for IE browser > `data-alt` attribute can be added to picture tag for use in `alt` attribute of lazy-loaded images ```html ``` When _lozad_ loads this picture element, it will fix it. If you want to use image placeholder (like low quality image placeholder), you can set a temporary `img` tag inside your `picture` tag. It will be removed when _lozad_ loads the picture element. ```html ``` ## Example with video ```html ``` ## Example with iframe ```html ``` That's all, just add the `lozad` class. ## Example toggling class ```html
``` The `active` class will be toggled on the element when it enters the browser’s viewport. ## Browser Support Available in [latest browsers](http://caniuse.com/#feat=intersectionobserver). If browser support is not available, then make use of [polyfill](https://www.npmjs.com/package/intersection-observer). For IE11 support, please make use of these [polyfills](https://polyfill.io/v3/polyfill.min.js?flags=gated&features=Object.assign%2CIntersectionObserver). ## FAQs Checkout the [FAQ Wiki](https://github.com/ApoorvSaxena/lozad.js/wiki/Frequently-Asked-Questions) for some common gotchas to be aware of while using **lozad.js** ## Contribute Interested in contributing features and fixes? [Read more on contributing](./CONTRIBUTING.md). ## Changelog See the [Changelog](https://github.com/ApoorvSaxena/lozad.js/wiki/Changelog) ## License [MIT](LICENSE) © [Apoorv Saxena](https://apoorv.pro) ================================================ FILE: bower.json ================================================ { "name": "lozad", "description": "A light-weight JS library to lazy load any HTML element such as images, ads, videos etc.", "main": "dist/lozad.js", "author": "Apoorv Saxena", "moduleType": [ "amd", "globals" ], "ignore": [ "CONTRIBUTING.md", "Gruntfile.js" ], "license": "MIT", "keywords": [ "lazy", "loader", "lazyloader", "lazyload", "performance", "image", "video", "iframe", "ads" ], "version": "1.2.0" } ================================================ FILE: demo/assets/css/ie8.css ================================================ /* Multiverse by HTML5 UP html5up.net | @ajlkn Free for personal and commercial use under the CCA 3.0 license (html5up.net/license) */ /* Button */ input[type="submit"], input[type="reset"], input[type="button"], button, .button { border: solid 2px #36383c; } input[type="submit"].special, input[type="reset"].special, input[type="button"].special, button.special, .button.special { border: 0; } /* Panel */ .panel { background: #242629; display: none; } .panel.active { display: block; } .panel > .closer:before { content: '\00d7'; font-size: 42px; } /* Main */ #main .thumb > h2 { text-align: center; width: 100%; left: 0; } ================================================ FILE: demo/assets/css/ie9.css ================================================ /* Multiverse by HTML5 UP html5up.net | @ajlkn Free for personal and commercial use under the CCA 3.0 license (html5up.net/license) */ /* Panel */ .panel > .inner.split:after { clear: both; content: ''; display: block; } .panel > .inner.split > div { float: left; margin-left: 0; padding-left: 0; } .panel > .inner.split > :first-child { padding-left: 0; } /* Wrapper */ #wrapper:before { display: none; } /* Main */ #main:after { clear: both; content: ''; display: block; } #main .thumb { float: left; } ================================================ FILE: demo/assets/css/main.css ================================================ /* Multiverse by HTML5 UP html5up.net | @ajlkn Free for personal and commercial use under the CCA 3.0 license (html5up.net/license) */ /* Reset */ html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td, article, aside, canvas, details, embed, figure, figcaption, footer, header, hgroup, menu, nav, output, ruby, section, summary, time, mark, audio, video { margin: 0; padding: 0; border: 0; font-size: 100%; font: inherit; vertical-align: baseline; } article, aside, details, figcaption, figure, footer, header, hgroup, menu, nav, section { display: block; } body { line-height: 1; } ol, ul { list-style: none; } blockquote, q { quotes: none; } blockquote:before, blockquote:after, q:before, q:after { content: ''; content: none; } table { border-collapse: collapse; border-spacing: 0; } body { -webkit-text-size-adjust: none; } img { width: 100%; height: 100%; } /* Box Model */ *, *:before, *:after { -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box; } @-moz-keyframes spinner { 0% { -moz-transform: rotate(0deg); -webkit-transform: rotate(0deg); -ms-transform: rotate(0deg); transform: rotate(0deg); } 100% { -moz-transform: rotate(359deg); -webkit-transform: rotate(359deg); -ms-transform: rotate(359deg); transform: rotate(359deg); } } @-webkit-keyframes spinner { 0% { -moz-transform: rotate(0deg); -webkit-transform: rotate(0deg); -ms-transform: rotate(0deg); transform: rotate(0deg); } 100% { -moz-transform: rotate(359deg); -webkit-transform: rotate(359deg); -ms-transform: rotate(359deg); transform: rotate(359deg); } } @-ms-keyframes spinner { 0% { -moz-transform: rotate(0deg); -webkit-transform: rotate(0deg); -ms-transform: rotate(0deg); transform: rotate(0deg); } 100% { -moz-transform: rotate(359deg); -webkit-transform: rotate(359deg); -ms-transform: rotate(359deg); transform: rotate(359deg); } } @keyframes spinner { 0% { -moz-transform: rotate(0deg); -webkit-transform: rotate(0deg); -ms-transform: rotate(0deg); transform: rotate(0deg); } 100% { -moz-transform: rotate(359deg); -webkit-transform: rotate(359deg); -ms-transform: rotate(359deg); transform: rotate(359deg); } } /* Basic */ @-ms-viewport { width: device-width; } body { -ms-overflow-style: scrollbar; } @media screen and (max-width: 480px) { html, body { min-width: 320px; } } body { background: #242629; } body.loading *, body.loading *:before, body.loading *:after { -moz-animation: none !important; -webkit-animation: none !important; -ms-animation: none !important; animation: none !important; -moz-transition: none !important; -webkit-transition: none !important; -ms-transition: none !important; transition: none !important; } body.resizing *, body.resizing *:before, body.resizing *:after { -moz-animation: none !important; -webkit-animation: none !important; -ms-animation: none !important; animation: none !important; -moz-transition: none !important; -webkit-transition: none !important; -ms-transition: none !important; transition: none !important; } /* Type */ body, input, select, textarea { color: #a0a0a1; font-family: "Source Sans Pro", Helvetica, sans-serif; font-size: 15pt; font-weight: 300; letter-spacing: 0.025em; line-height: 1.65; } @media screen and (max-width: 1680px) { body, input, select, textarea { font-size: 11pt; } } a { -moz-transition: color 0.2s ease-in-out, border-bottom-color 0.2s ease-in-out; -webkit-transition: color 0.2s ease-in-out, border-bottom-color 0.2s ease-in-out; -ms-transition: color 0.2s ease-in-out, border-bottom-color 0.2s ease-in-out; transition: color 0.2s ease-in-out, border-bottom-color 0.2s ease-in-out; border-bottom: dotted 1px; color: #34a58e; text-decoration: none; } a:hover { border-bottom-color: transparent; color: #34a58e !important; } strong, b { color: #ffffff; font-weight: 300; } em, i { font-style: italic; } p { margin: 0 0 2em 0; } h1, h2, h3, h4, h5, h6 { color: #ffffff; font-weight: 300; letter-spacing: 0.1em; line-height: 1.5; margin: 0 0 1em 0; text-transform: uppercase; } h1 a, h2 a, h3 a, h4 a, h5 a, h6 a { color: inherit; text-decoration: none; } h1 { font-size: 2em; } h2 { font-size: 1.25em; } h3 { font-size: 1.1em; } h4 { font-size: 1em; } h5 { font-size: 0.9em; } h6 { font-size: 0.7em; } @media screen and (max-width: 736px) { h2 { font-size: 1em; } h3 { font-size: 0.9em; } h4 { font-size: 0.8em; } h5 { font-size: 0.7em; } h6 { font-size: 0.7em; } } sub { font-size: 0.8em; position: relative; top: 0.5em; } sup { font-size: 0.8em; position: relative; top: -0.5em; } blockquote { border-left: 4px #36383c; font-style: italic; margin: 0 0 2em 0; padding: 0.5em 0 0.5em 2em; } code { background: #34363b; border: solid 1px #36383c; font-family: "Courier New", monospace; font-size: 0.9em; margin: 0 0.25em; padding: 0.25em 0.65em; } pre { -webkit-overflow-scrolling: touch; font-family: "Courier New", monospace; font-size: 0.9em; margin: 0 0 2em 0; } pre code { display: block; line-height: 1.75; padding: 1em 1.5em; overflow-x: auto; } hr { border: 0; border-bottom: solid 1px #36383c; margin: 2em 0; } hr.major { margin: 3em 0; } .align-left { text-align: left; } .align-center { text-align: center; } .align-right { text-align: right; } /* Wrapper */ #wrapper { -moz-transition: -moz-filter 0.5s ease, -webkit-filter 0.5s ease, -ms-filter 0.5s ease, -moz-filter 0.5s ease; -webkit-transition: -moz-filter 0.5s ease, -webkit-filter 0.5s ease, -ms-filter 0.5s ease, -webkit-filter 0.5s ease; -ms-transition: -moz-filter 0.5s ease, -webkit-filter 0.5s ease, -ms-filter 0.5s ease, -ms-filter 0.5s ease; transition: -moz-filter 0.5s ease, -webkit-filter 0.5s ease, -ms-filter 0.5s ease, filter 0.5s ease; position: relative; } #wrapper:after { -moz-pointer-events: none; -webkit-pointer-events: none; -ms-pointer-events: none; pointer-events: none; -moz-transition: opacity 0.5s ease, visibility 0.5s; -webkit-transition: opacity 0.5s ease, visibility 0.5s; -ms-transition: opacity 0.5s ease, visibility 0.5s; transition: opacity 0.5s ease, visibility 0.5s; background: rgba(36, 38, 41, 0.5); content: ''; display: block; height: 100%; left: 0; opacity: 0; position: absolute; top: 0; visibility: hidden; width: 100%; z-index: 1; } body.ie #wrapper:after { background: rgba(36, 38, 41, 0.8); } body.modal-active #wrapper { -moz-filter: blur(8px); -webkit-filter: blur(8px); -ms-filter: blur(8px); filter: blur(8px); } body.modal-active #wrapper:after { -moz-pointer-events: auto; -webkit-pointer-events: auto; -ms-pointer-events: auto; pointer-events: auto; opacity: 1; visibility: visible; z-index: 10003; } #wrapper:before { -moz-animation: spinner 1s infinite linear !important; -webkit-animation: spinner 1s infinite linear !important; -ms-animation: spinner 1s infinite linear !important; animation: spinner 1s infinite linear !important; -moz-pointer-events: none; -webkit-pointer-events: none; -ms-pointer-events: none; pointer-events: none; -moz-transition: top 0.75s ease-in-out, opacity 0.35s ease-out, visibility 0.35s; -webkit-transition: top 0.75s ease-in-out, opacity 0.35s ease-out, visibility 0.35s; -ms-transition: top 0.75s ease-in-out, opacity 0.35s ease-out, visibility 0.35s; transition: top 0.75s ease-in-out, opacity 0.35s ease-out, visibility 0.35s; background-image: url("images/spinner.svg"); background-position: center; background-repeat: no-repeat; background-size: contain; content: ''; display: block; font-size: 2em; height: 2em; left: 50%; line-height: 2em; margin: -1em 0 0 -1em; opacity: 0; position: fixed; text-align: center; top: 75%; visibility: hidden; width: 2em; } body.loading #wrapper:before { -moz-transition: opacity 1s ease-out !important; -webkit-transition: opacity 1s ease-out !important; -ms-transition: opacity 1s ease-out !important; transition: opacity 1s ease-out !important; -moz-transition-delay: 0.5s !important; -webkit-transition-delay: 0.5s !important; -ms-transition-delay: 0.5s !important; transition-delay: 0.5s !important; opacity: 0.25; top: 50%; visibility: visible; } /* Header */ body { padding: 0 0 4em 0; } #header { -moz-transform: translateY(0); -webkit-transform: translateY(0); -ms-transform: translateY(0); transform: translateY(0); -moz-transition: -moz-transform 1s ease; -webkit-transition: -webkit-transform 1s ease; -ms-transition: -ms-transform 1s ease; transition: transform 1s ease; -moz-user-select: none; -ms-user-select: none; -webkit-user-select: none; background: #1f2224; bottom: -1em; height: 5em; left: 0; line-height: 4em; padding: 0 1.5em; position: fixed; user-select: none; width: 100%; z-index: 10002; } body.loading #header { -moz-transform: translateY(4em); -webkit-transform: translateY(4em); -ms-transform: translateY(4em); transform: translateY(4em); } #header h1 { color: #a0a0a1; display: inline-block; font-size: 1em; line-height: 1; margin: 0; vertical-align: middle; } #header h1 a { border: 0; color: inherit; } #header h1 a:hover { color: inherit !important; } #header nav { position: absolute; right: 0; top: 0; } #header nav > ul { list-style: none; margin: 0; padding: 0; } #header nav > ul > li { display: inline-block; padding: 0; } #header nav > ul > li a { -moz-transition: background-color 0.5s ease; -webkit-transition: background-color 0.5s ease; -ms-transition: background-color 0.5s ease; transition: background-color 0.5s ease; border: 0; color: #ffffff; display: inline-block; letter-spacing: 0.1em; padding: 0 1.65em; text-transform: uppercase; } #header nav > ul > li a.icon:before { color: #505051; float: right; margin-left: 0.75em; } #header nav > ul > li a:hover { color: #ffffff !important; } #header nav > ul > li a.active { background-color: #242629; } @media screen and (max-width: 736px) { body { padding: 4em 0 0 0; } #header { -moz-transform: translateY(0); -webkit-transform: translateY(0); -ms-transform: translateY(0); transform: translateY(0); bottom: auto; height: 4em; padding: 0 1em; top: 0; } body.loading #header { -moz-transform: translateY(-3.4em); -webkit-transform: translateY(-3.4em); -ms-transform: translateY(-3.4em); transform: translateY(-3.4em); } #header h1 { font-size: 0.9em; } #header nav > ul > li a { font-size: 0.9em; padding: 0 1.15em; } } /* Main */ #main, .sub-main { -moz-transition: -moz-filter 0.5s ease, -webkit-filter 0.5s ease, -ms-filter 0.5s ease, -moz-filter 0.5s ease; -webkit-transition: -moz-filter 0.5s ease, -webkit-filter 0.5s ease, -ms-filter 0.5s ease, -webkit-filter 0.5s ease; -ms-transition: -moz-filter 0.5s ease, -webkit-filter 0.5s ease, -ms-filter 0.5s ease, -ms-filter 0.5s ease; transition: -moz-filter 0.5s ease, -webkit-filter 0.5s ease, -ms-filter 0.5s ease, filter 0.5s ease; display: -moz-flex; display: -webkit-flex; display: -ms-flex; display: flex; -moz-flex-wrap: wrap; -webkit-flex-wrap: wrap; -ms-flex-wrap: wrap; flex-wrap: wrap; -webkit-tap-highlight-color: rgba(255, 255, 255, 0); } #main .thumb { -moz-transition: opacity 1.25s ease-in-out; -webkit-transition: opacity 1.25s ease-in-out; -ms-transition: opacity 1.25s ease-in-out; transition: opacity 1.25s ease-in-out; -moz-pointer-events: auto; -webkit-pointer-events: auto; -ms-pointer-events: auto; pointer-events: auto; -webkit-tap-highlight-color: rgba(255, 255, 255, 0); opacity: 1; overflow: hidden; position: relative; } #main .thumb:after { background-image: -moz-linear-gradient(to top, rgba(10, 17, 25, 0.35) 5%, rgba(10, 17, 25, 0) 35%); background-image: -webkit-linear-gradient(to top, rgba(10, 17, 25, 0.35) 5%, rgba(10, 17, 25, 0) 35%); background-image: -ms-linear-gradient(to top, rgba(10, 17, 25, 0.35) 5%, rgba(10, 17, 25, 0) 35%); background-image: linear-gradient(to top, rgba(10, 17, 25, 0.35) 5%, rgba(10, 17, 25, 0) 35%); -moz-pointer-events: none; -webkit-pointer-events: none; -ms-pointer-events: none; pointer-events: none; background-size: cover; content: ''; display: block; height: 100%; left: 0; position: absolute; top: 0; width: 100%; } #main .thumb > .image { -webkit-tap-highlight-color: rgba(255, 255, 255, 0); background-position: center; background-repeat: no-repeat; background-size: cover; border: 0; height: 100%; left: 0; position: absolute; top: 0; width: 100%; } #main .thumb > h2 { -moz-pointer-events: none; -webkit-pointer-events: none; -ms-pointer-events: none; pointer-events: none; bottom: 1.875em; font-size: 0.8em; left: 2.1875em; margin: 0; position: absolute; z-index: 1; } #main .thumb > p { display: none; } #main:after { -moz-pointer-events: none; -webkit-pointer-events: none; -ms-pointer-events: none; pointer-events: none; -moz-transition: opacity 0.5s ease, visibility 0.5s; -webkit-transition: opacity 0.5s ease, visibility 0.5s; -ms-transition: opacity 0.5s ease, visibility 0.5s; transition: opacity 0.5s ease, visibility 0.5s; background: rgba(36, 38, 41, 0.25); content: ''; display: block; height: 100%; left: 0; opacity: 0; position: absolute; top: 0; visibility: hidden; width: 100%; z-index: 1; } body.ie #main:after { background: rgba(36, 38, 41, 0.55); } body.content-active #main { -moz-filter: blur(6px); -webkit-filter: blur(6px); -ms-filter: blur(6px); filter: blur(6px); } body.content-active #main:after { -moz-pointer-events: auto; -webkit-pointer-events: auto; -ms-pointer-events: auto; pointer-events: auto; opacity: 1; visibility: visible; } body.loading #main .thumb { -moz-pointer-events: none; -webkit-pointer-events: none; -ms-pointer-events: none; pointer-events: none; opacity: 0; } #main .thumb { -moz-transition-delay: 2.525s; -webkit-transition-delay: 2.525s; -ms-transition-delay: 2.525s; transition-delay: 2.525s; height: calc(40vh - 2em); min-height: 20em; width: 25%; } #main .thumb:nth-child(1) { -moz-transition-delay: 0.65s; -webkit-transition-delay: 0.65s; -ms-transition-delay: 0.65s; transition-delay: 0.65s; } #main .thumb:nth-child(2) { -moz-transition-delay: 0.8s; -webkit-transition-delay: 0.8s; -ms-transition-delay: 0.8s; transition-delay: 0.8s; } #main .thumb:nth-child(3) { -moz-transition-delay: 0.95s; -webkit-transition-delay: 0.95s; -ms-transition-delay: 0.95s; transition-delay: 0.95s; } #main .thumb:nth-child(4) { -moz-transition-delay: 1.1s; -webkit-transition-delay: 1.1s; -ms-transition-delay: 1.1s; transition-delay: 1.1s; } #main .thumb:nth-child(5) { -moz-transition-delay: 1.25s; -webkit-transition-delay: 1.25s; -ms-transition-delay: 1.25s; transition-delay: 1.25s; } #main .thumb:nth-child(6) { -moz-transition-delay: 1.4s; -webkit-transition-delay: 1.4s; -ms-transition-delay: 1.4s; transition-delay: 1.4s; } #main .thumb:nth-child(7) { -moz-transition-delay: 1.55s; -webkit-transition-delay: 1.55s; -ms-transition-delay: 1.55s; transition-delay: 1.55s; } #main .thumb:nth-child(8) { -moz-transition-delay: 1.7s; -webkit-transition-delay: 1.7s; -ms-transition-delay: 1.7s; transition-delay: 1.7s; } #main .thumb:nth-child(9) { -moz-transition-delay: 1.85s; -webkit-transition-delay: 1.85s; -ms-transition-delay: 1.85s; transition-delay: 1.85s; } #main .thumb:nth-child(10) { -moz-transition-delay: 2s; -webkit-transition-delay: 2s; -ms-transition-delay: 2s; transition-delay: 2s; } #main .thumb:nth-child(11) { -moz-transition-delay: 2.15s; -webkit-transition-delay: 2.15s; -ms-transition-delay: 2.15s; transition-delay: 2.15s; } #main .thumb:nth-child(12) { -moz-transition-delay: 2.3s; -webkit-transition-delay: 2.3s; -ms-transition-delay: 2.3s; transition-delay: 2.3s; } /* Pictures */ #pictures .screen { min-height: 100vh; display: -webkit-box; display: -ms-flexbox; display: flex; -ms-flex-wrap: wrap; flex-wrap: wrap; -webkit-box-align: center; -ms-flex-align: center; align-items: center; -webkit-box-pack: center; -ms-flex-pack: center; justify-content: center; } #pictures .picture { max-width: 400px; margin: 3rem; } /* Backgrounds */ #backgrounds .screen { min-height: 100vh; display: -webkit-box; display: -ms-flexbox; display: flex; -ms-flex-wrap: wrap; flex-wrap: wrap; -webkit-box-align: center; -ms-flex-align: center; align-items: center; -webkit-box-pack: center; -ms-flex-pack: center; justify-content: center; } #backgrounds .background { max-width: 400px; margin: 3rem; } #backgrounds .lozad-background { display: block; min-height: 12rem; min-width: 240px; background-size: contain; background-repeat: no-repeat; background-position: 50% 50%; } /* iframes & video */ #iframe .frame, #video .frame { display: -webkit-box; display: -ms-flexbox; display: flex; -ms-flex-wrap: wrap; flex-wrap: wrap; -webkit-box-align: center; -ms-flex-align: center; align-items: center; -webkit-box-pack: center; -ms-flex-pack: center; justify-content: center; margin-bottom: 10vh; } .video-example{ margin: 0 15px; } @media screen and (max-width: 1680px) { #main .thumb { -moz-transition-delay: 2.075s; -webkit-transition-delay: 2.075s; -ms-transition-delay: 2.075s; transition-delay: 2.075s; height: calc(40vh - 2em); min-height: 20em; width: 33.33333%; } #main .thumb:nth-child(1) { -moz-transition-delay: 0.65s; -webkit-transition-delay: 0.65s; -ms-transition-delay: 0.65s; transition-delay: 0.65s; } #main .thumb:nth-child(2) { -moz-transition-delay: 0.8s; -webkit-transition-delay: 0.8s; -ms-transition-delay: 0.8s; transition-delay: 0.8s; } #main .thumb:nth-child(3) { -moz-transition-delay: 0.95s; -webkit-transition-delay: 0.95s; -ms-transition-delay: 0.95s; transition-delay: 0.95s; } #main .thumb:nth-child(4) { -moz-transition-delay: 1.1s; -webkit-transition-delay: 1.1s; -ms-transition-delay: 1.1s; transition-delay: 1.1s; } #main .thumb:nth-child(5) { -moz-transition-delay: 1.25s; -webkit-transition-delay: 1.25s; -ms-transition-delay: 1.25s; transition-delay: 1.25s; } #main .thumb:nth-child(6) { -moz-transition-delay: 1.4s; -webkit-transition-delay: 1.4s; -ms-transition-delay: 1.4s; transition-delay: 1.4s; } #main .thumb:nth-child(7) { -moz-transition-delay: 1.55s; -webkit-transition-delay: 1.55s; -ms-transition-delay: 1.55s; transition-delay: 1.55s; } #main .thumb:nth-child(8) { -moz-transition-delay: 1.7s; -webkit-transition-delay: 1.7s; -ms-transition-delay: 1.7s; transition-delay: 1.7s; } #main .thumb:nth-child(9) { -moz-transition-delay: 1.85s; -webkit-transition-delay: 1.85s; -ms-transition-delay: 1.85s; transition-delay: 1.85s; } } @media screen and (max-width: 1280px) { #main .thumb { -moz-transition-delay: 1.625s; -webkit-transition-delay: 1.625s; -ms-transition-delay: 1.625s; transition-delay: 1.625s; height: calc(40vh - 2em); min-height: 20em; width: 50%; } #main .thumb:nth-child(1) { -moz-transition-delay: 0.65s; -webkit-transition-delay: 0.65s; -ms-transition-delay: 0.65s; transition-delay: 0.65s; } #main .thumb:nth-child(2) { -moz-transition-delay: 0.8s; -webkit-transition-delay: 0.8s; -ms-transition-delay: 0.8s; transition-delay: 0.8s; } #main .thumb:nth-child(3) { -moz-transition-delay: 0.95s; -webkit-transition-delay: 0.95s; -ms-transition-delay: 0.95s; transition-delay: 0.95s; } #main .thumb:nth-child(4) { -moz-transition-delay: 1.1s; -webkit-transition-delay: 1.1s; -ms-transition-delay: 1.1s; transition-delay: 1.1s; } #main .thumb:nth-child(5) { -moz-transition-delay: 1.25s; -webkit-transition-delay: 1.25s; -ms-transition-delay: 1.25s; transition-delay: 1.25s; } #main .thumb:nth-child(6) { -moz-transition-delay: 1.4s; -webkit-transition-delay: 1.4s; -ms-transition-delay: 1.4s; transition-delay: 1.4s; } } @media screen and (max-width: 980px) { #main .thumb { -moz-transition-delay: 2.075s; -webkit-transition-delay: 2.075s; -ms-transition-delay: 2.075s; transition-delay: 2.075s; height: calc(28.57143vh - 1.33333em); min-height: 18em; width: 50%; } #main .thumb:nth-child(1) { -moz-transition-delay: 0.65s; -webkit-transition-delay: 0.65s; -ms-transition-delay: 0.65s; transition-delay: 0.65s; } #main .thumb:nth-child(2) { -moz-transition-delay: 0.8s; -webkit-transition-delay: 0.8s; -ms-transition-delay: 0.8s; transition-delay: 0.8s; } #main .thumb:nth-child(3) { -moz-transition-delay: 0.95s; -webkit-transition-delay: 0.95s; -ms-transition-delay: 0.95s; transition-delay: 0.95s; } #main .thumb:nth-child(4) { -moz-transition-delay: 1.1s; -webkit-transition-delay: 1.1s; -ms-transition-delay: 1.1s; transition-delay: 1.1s; } #main .thumb:nth-child(5) { -moz-transition-delay: 1.25s; -webkit-transition-delay: 1.25s; -ms-transition-delay: 1.25s; transition-delay: 1.25s; } #main .thumb:nth-child(6) { -moz-transition-delay: 1.4s; -webkit-transition-delay: 1.4s; -ms-transition-delay: 1.4s; transition-delay: 1.4s; } #main .thumb:nth-child(7) { -moz-transition-delay: 1.55s; -webkit-transition-delay: 1.55s; -ms-transition-delay: 1.55s; transition-delay: 1.55s; } #main .thumb:nth-child(8) { -moz-transition-delay: 1.7s; -webkit-transition-delay: 1.7s; -ms-transition-delay: 1.7s; transition-delay: 1.7s; } #main .thumb:nth-child(9) { -moz-transition-delay: 1.85s; -webkit-transition-delay: 1.85s; -ms-transition-delay: 1.85s; transition-delay: 1.85s; } } @media screen and (max-width: 480px) { #main .thumb { -moz-transition-delay: 1.175s; -webkit-transition-delay: 1.175s; -ms-transition-delay: 1.175s; transition-delay: 1.175s; height: calc(40vh - 2em); min-height: 18em; width: 100%; } #main .thumb:nth-child(1) { -moz-transition-delay: 0.65s; -webkit-transition-delay: 0.65s; -ms-transition-delay: 0.65s; transition-delay: 0.65s; } #main .thumb:nth-child(2) { -moz-transition-delay: 0.8s; -webkit-transition-delay: 0.8s; -ms-transition-delay: 0.8s; transition-delay: 0.8s; } #main .thumb:nth-child(3) { -moz-transition-delay: 0.95s; -webkit-transition-delay: 0.95s; -ms-transition-delay: 0.95s; transition-delay: 0.95s; } } .social-wrap { margin-top: 5px; } #header nav > ul > li > .social-wrap a { padding: 0 0.5em; } svg { fill: rgba(255, 255, 255, 0.6); } svg:hover { fill: #fff; } .main-heading { text-align: center; margin: 100px 10px; height: 100%; width: 100%; } ================================================ FILE: demo/assets/js/ie/html5shiv.js ================================================ /* HTML5 Shiv v3.6.2 | @afarkas @jdalton @jon_neal @rem | MIT/GPL2 Licensed */ (function(l,f){function m(){var a=e.elements;return"string"==typeof a?a.split(" "):a}function i(a){var b=n[a[o]];b||(b={},h++,a[o]=h,n[h]=b);return b}function p(a,b,c){b||(b=f);if(g)return b.createElement(a);c||(c=i(b));b=c.cache[a]?c.cache[a].cloneNode():r.test(a)?(c.cache[a]=c.createElem(a)).cloneNode():c.createElem(a);return b.canHaveChildren&&!s.test(a)?c.frag.appendChild(b):b}function t(a,b){if(!b.cache)b.cache={},b.createElem=a.createElement,b.createFrag=a.createDocumentFragment,b.frag=b.createFrag(); a.createElement=function(c){return!e.shivMethods?b.createElem(c):p(c,a,b)};a.createDocumentFragment=Function("h,f","return function(){var n=f.cloneNode(),c=n.createElement;h.shivMethods&&("+m().join().replace(/\w+/g,function(a){b.createElem(a);b.frag.createElement(a);return'c("'+a+'")'})+");return n}")(e,b.frag)}function q(a){a||(a=f);var b=i(a);if(e.shivCSS&&!j&&!b.hasCSS){var c,d=a;c=d.createElement("p");d=d.getElementsByTagName("head")[0]||d.documentElement;c.innerHTML="x"; c=d.insertBefore(c.lastChild,d.firstChild);b.hasCSS=!!c}g||t(a,b);return a}var k=l.html5||{},s=/^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i,r=/^(?:a|b|code|div|fieldset|h1|h2|h3|h4|h5|h6|i|label|li|ol|p|q|span|strong|style|table|tbody|td|th|tr|ul)$/i,j,o="_html5shiv",h=0,n={},g;(function(){try{var a=f.createElement("a");a.innerHTML="";j="hidden"in a;var b;if(!(b=1==a.childNodes.length)){f.createElement("a");var c=f.createDocumentFragment();b="undefined"==typeof c.cloneNode|| "undefined"==typeof c.createDocumentFragment||"undefined"==typeof c.createElement}g=b}catch(d){g=j=!0}})();var e={elements:k.elements||"abbr article aside audio bdi canvas data datalist details figcaption figure footer header hgroup main mark meter nav output progress section summary time video",version:"3.6.2",shivCSS:!1!==k.shivCSS,supportsUnknownElements:g,shivMethods:!1!==k.shivMethods,type:"default",shivDocument:q,createElement:p,createDocumentFragment:function(a,b){a||(a=f);if(g)return a.createDocumentFragment(); for(var b=b||i(a),c=b.frag.cloneNode(),d=0,e=m(),h=e.length;d').appendTo($this); // Closer. $closer .on('click', function(event) { $this.trigger('---hide'); }); // Events. $this .on('click', function(event) { event.stopPropagation(); }) .on('---toggle', function() { if ($this.hasClass('active')) $this.triggerHandler('---hide'); else $this.triggerHandler('---show'); }) .on('---show', function() { // Hide other content. if ($body.hasClass('content-active')) $panels.trigger('---hide'); // Activate content, toggles. $this.addClass('active'); $toggles.addClass('active'); // Activate body. $body.addClass('content-active'); }) .on('---hide', function() { // Deactivate content, toggles. $this.removeClass('active'); $toggles.removeClass('active'); // Deactivate body. $body.removeClass('content-active'); }); // Toggles. $toggles .removeAttr('href') .css('cursor', 'pointer') .on('click', function(event) { event.preventDefault(); event.stopPropagation(); $this.trigger('---toggle'); }); }); // Global events. $body .on('click', function(event) { if ($body.hasClass('content-active')) { event.preventDefault(); event.stopPropagation(); $panels.trigger('---hide'); } }); $window .on('keyup', function(event) { if (event.keyCode == 27 && $body.hasClass('content-active')) { event.preventDefault(); event.stopPropagation(); $panels.trigger('---hide'); } }); // Header. var $header = $('#header'); // Links. $header.find('a').each(function() { var $this = $(this), href = $this.attr('href'); // Internal link? Skip. if (!href || href.charAt(0) == '#') return; // Redirect on click. $this .removeAttr('href') .css('cursor', 'pointer') .on('click', function(event) { event.preventDefault(); event.stopPropagation(); window.location.href = href; }); }); // Footer. var $footer = $('#footer'); // Copyright. // This basically just moves the copyright line to the end of the *last* sibling of its current parent // when the "medium" breakpoint activates, and moves it back when it deactivates. $footer.find('.copyright').each(function() { var $this = $(this), $parent = $this.parent(), $lastParent = $parent.parent().children().last(); skel .on('+medium', function() { $this.appendTo($lastParent); }) .on('-medium', function() { $this.appendTo($parent); }); }); // Main. var $main = $('#main'); // Thumbs. $main.children('.thumb').each(function() { var $this = $(this), $image = $this.find('.image'), $image_img = $image.children('img'), x; // No image? Bail. if ($image.length == 0) return; // Image. // This sets the background of the "image" to the image pointed to by its child // (which is then hidden). Gives us way more flexibility. // Set background. $image.css('background-image', 'url(' + $image_img.attr('src') + ')'); // Set background position. if (x = $image_img.data('position')) $image.css('background-position', x); // Hide original img. $image_img.hide(); // Hack: IE<11 doesn't support pointer-events, which means clicks to our image never // land as they're blocked by the thumbnail's caption overlay gradient. This just forces // the click through to the image. if (skel.vars.IEVersion < 11) $this .css('cursor', 'pointer') .on('click', function() { $image.trigger('click'); }); }); }); })(jQuery); ================================================ FILE: demo/index.html ================================================ Lozad.js: Highly performant lazy loader

Lozad.js - Performant Lazy Loading Library

Image 1

Image 2

Image 3

Image 4

Image 5

Image 6

Image 7

Image 8

Image 9

Image 10

Image 11

Image 12

<picture> example

* You can open your network section in dev tools, for see how images are loading

Example 1

picture-01.jpg media="(min-width: 1280px)"
picture-02.jpg media="(min-width: 980px)"
picture-03.jpg media="(min-width: 320px)"
                    

Example 2

picture-04.jpg media="(min-width: 1280px)"
picture-05.jpg media="(min-width: 980px)"
picture-06.jpg media="(min-width: 320px)"
                    

Example 3

picture-07.jpg media="(min-width: 1280px)"
picture-08.jpg media="(min-width: 980px)"
picture-09.jpg media="(min-width: 320px)"
                    

<background> example

* You can open your network section in dev tools, for see how background-images are loading

Example 1

Single Background Image
                    

Example 2

Multiple Background Images
Check the console to see that these are indeed separate images.
                    

Example 3

Multiple Background Images
Fallback Method ( where the first / foremost image fails )
Check the console to see that the first image is failed to load.
                    

Example 4

Responsive Background Images set
Change a device pixel ratio with devtools and check the console to see which image dimension was loaded
                    

<iframe> example

<video> example

video courtesy of Big Buck Bunny.

normal video example
================================================ FILE: dist/lozad.es.js ================================================ /*! lozad.js - v1.16.0 - 2020-09-10 * https://github.com/ApoorvSaxena/lozad.js * Copyright (c) 2020 Apoorv Saxena; Licensed MIT */ /** * Detect IE browser * @const {boolean} * @private */ const isIE = typeof document !== 'undefined' && document.documentMode; /** * * @param {string} type * */ const support = type => window && window[type]; const validAttribute = ['data-iesrc', 'data-alt', 'data-src', 'data-srcset', 'data-background-image', 'data-toggle-class']; const defaultConfig = { rootMargin: '0px', threshold: 0, enableAutoReload: false, load(element) { if (element.nodeName.toLowerCase() === 'picture') { let img = element.querySelector('img'); let append = false; if (img === null) { img = document.createElement('img'); append = true; } if (isIE && element.getAttribute('data-iesrc')) { img.src = element.getAttribute('data-iesrc'); } if (element.getAttribute('data-alt')) { img.alt = element.getAttribute('data-alt'); } if (append) { element.append(img); } } if (element.nodeName.toLowerCase() === 'video' && !element.getAttribute('data-src')) { if (element.children) { const childs = element.children; let childSrc; for (let i = 0; i <= childs.length - 1; i++) { childSrc = childs[i].getAttribute('data-src'); if (childSrc) { childs[i].src = childSrc; } } element.load(); } } if (element.getAttribute('data-poster')) { element.poster = element.getAttribute('data-poster'); } if (element.getAttribute('data-src')) { element.src = element.getAttribute('data-src'); } if (element.getAttribute('data-srcset')) { element.setAttribute('srcset', element.getAttribute('data-srcset')); } let backgroundImageDelimiter = ','; if (element.getAttribute('data-background-delimiter')) { backgroundImageDelimiter = element.getAttribute('data-background-delimiter'); } if (element.getAttribute('data-background-image')) { element.style.backgroundImage = `url('${element.getAttribute('data-background-image').split(backgroundImageDelimiter).join('\'),url(\'')}')`; } else if (element.getAttribute('data-background-image-set')) { const imageSetLinks = element.getAttribute('data-background-image-set').split(backgroundImageDelimiter); let firstUrlLink = (imageSetLinks[0].substr(0, imageSetLinks[0].indexOf(' ')) || imageSetLinks[0]); // Substring before ... 1x firstUrlLink = firstUrlLink.indexOf('url(') === -1 ? `url(${firstUrlLink})` : firstUrlLink; if (imageSetLinks.length === 1) { element.style.backgroundImage = firstUrlLink; } else { element.setAttribute('style', (element.getAttribute('style') || '') + `background-image: ${firstUrlLink}; background-image: -webkit-image-set(${imageSetLinks}); background-image: image-set(${imageSetLinks})`); } } if (element.getAttribute('data-toggle-class')) { element.classList.toggle(element.getAttribute('data-toggle-class')); } }, loaded() {} }; function markAsLoaded(element) { element.setAttribute('data-loaded', true); } function preLoad(element) { if (element.getAttribute('data-placeholder-background')) { element.style.background = element.getAttribute('data-placeholder-background'); } } const isLoaded = element => element.getAttribute('data-loaded') === 'true'; const onIntersection = (load, loaded) => (entries, observer) => { entries.forEach(entry => { if (entry.intersectionRatio > 0 || entry.isIntersecting) { observer.unobserve(entry.target); if (!isLoaded(entry.target)) { load(entry.target); markAsLoaded(entry.target); loaded(entry.target); } } }); }; const onMutation = load => entries => { entries.forEach(entry => { if (isLoaded(entry.target) && entry.type === 'attributes' && validAttribute.indexOf(entry.attributeName) > -1) { load(entry.target); } }); }; const getElements = (selector, root = document) => { if (selector instanceof Element) { return [selector] } if (selector instanceof NodeList) { return selector } return root.querySelectorAll(selector) }; function lozad (selector = '.lozad', options = {}) { const {root, rootMargin, threshold, enableAutoReload, load, loaded} = Object.assign({}, defaultConfig, options); let observer; let mutationObserver; if (support('IntersectionObserver')) { observer = new IntersectionObserver(onIntersection(load, loaded), { root, rootMargin, threshold }); } if (support('MutationObserver') && enableAutoReload) { mutationObserver = new MutationObserver(onMutation(load, loaded)); } const elements = getElements(selector, root); for (let i = 0; i < elements.length; i++) { preLoad(elements[i]); } return { observe() { const elements = getElements(selector, root); for (let i = 0; i < elements.length; i++) { if (isLoaded(elements[i])) { continue } if (observer) { if (mutationObserver && enableAutoReload) { mutationObserver.observe(elements[i], {subtree: true, attributes: true, attributeFilter: validAttribute}); } observer.observe(elements[i]); continue } load(elements[i]); markAsLoaded(elements[i]); loaded(elements[i]); } }, triggerLoad(element) { if (isLoaded(element)) { return } load(element); markAsLoaded(element); loaded(element); }, observer, mutationObserver } } export default lozad; ================================================ FILE: dist/lozad.js ================================================ /*! lozad.js - v1.16.0 - 2020-09-10 * https://github.com/ApoorvSaxena/lozad.js * Copyright (c) 2020 Apoorv Saxena; Licensed MIT */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global.lozad = factory()); }(this, (function () { 'use strict'; /** * Detect IE browser * @const {boolean} * @private */ var isIE = typeof document !== 'undefined' && document.documentMode; /** * * @param {string} type * */ var support = function support(type) { return window && window[type]; }; var validAttribute = ['data-iesrc', 'data-alt', 'data-src', 'data-srcset', 'data-background-image', 'data-toggle-class']; var defaultConfig = { rootMargin: '0px', threshold: 0, enableAutoReload: false, load: function load(element) { if (element.nodeName.toLowerCase() === 'picture') { var img = element.querySelector('img'); var append = false; if (img === null) { img = document.createElement('img'); append = true; } if (isIE && element.getAttribute('data-iesrc')) { img.src = element.getAttribute('data-iesrc'); } if (element.getAttribute('data-alt')) { img.alt = element.getAttribute('data-alt'); } if (append) { element.append(img); } } if (element.nodeName.toLowerCase() === 'video' && !element.getAttribute('data-src')) { if (element.children) { var childs = element.children; var childSrc = void 0; for (var i = 0; i <= childs.length - 1; i++) { childSrc = childs[i].getAttribute('data-src'); if (childSrc) { childs[i].src = childSrc; } } element.load(); } } if (element.getAttribute('data-poster')) { element.poster = element.getAttribute('data-poster'); } if (element.getAttribute('data-src')) { element.src = element.getAttribute('data-src'); } if (element.getAttribute('data-srcset')) { element.setAttribute('srcset', element.getAttribute('data-srcset')); } var backgroundImageDelimiter = ','; if (element.getAttribute('data-background-delimiter')) { backgroundImageDelimiter = element.getAttribute('data-background-delimiter'); } if (element.getAttribute('data-background-image')) { element.style.backgroundImage = 'url(\'' + element.getAttribute('data-background-image').split(backgroundImageDelimiter).join('\'),url(\'') + '\')'; } else if (element.getAttribute('data-background-image-set')) { var imageSetLinks = element.getAttribute('data-background-image-set').split(backgroundImageDelimiter); var firstUrlLink = imageSetLinks[0].substr(0, imageSetLinks[0].indexOf(' ')) || imageSetLinks[0]; // Substring before ... 1x firstUrlLink = firstUrlLink.indexOf('url(') === -1 ? 'url(' + firstUrlLink + ')' : firstUrlLink; if (imageSetLinks.length === 1) { element.style.backgroundImage = firstUrlLink; } else { element.setAttribute('style', (element.getAttribute('style') || '') + ('background-image: ' + firstUrlLink + '; background-image: -webkit-image-set(' + imageSetLinks + '); background-image: image-set(' + imageSetLinks + ')')); } } if (element.getAttribute('data-toggle-class')) { element.classList.toggle(element.getAttribute('data-toggle-class')); } }, loaded: function loaded() {} }; function markAsLoaded(element) { element.setAttribute('data-loaded', true); } function preLoad(element) { if (element.getAttribute('data-placeholder-background')) { element.style.background = element.getAttribute('data-placeholder-background'); } } var isLoaded = function isLoaded(element) { return element.getAttribute('data-loaded') === 'true'; }; var onIntersection = function onIntersection(load, loaded) { return function (entries, observer) { entries.forEach(function (entry) { if (entry.intersectionRatio > 0 || entry.isIntersecting) { observer.unobserve(entry.target); if (!isLoaded(entry.target)) { load(entry.target); markAsLoaded(entry.target); loaded(entry.target); } } }); }; }; var onMutation = function onMutation(load) { return function (entries) { entries.forEach(function (entry) { if (isLoaded(entry.target) && entry.type === 'attributes' && validAttribute.indexOf(entry.attributeName) > -1) { load(entry.target); } }); }; }; var getElements = function getElements(selector) { var root = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : document; if (selector instanceof Element) { return [selector]; } if (selector instanceof NodeList) { return selector; } return root.querySelectorAll(selector); }; function lozad () { var selector = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '.lozad'; var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var _Object$assign = Object.assign({}, defaultConfig, options), root = _Object$assign.root, rootMargin = _Object$assign.rootMargin, threshold = _Object$assign.threshold, enableAutoReload = _Object$assign.enableAutoReload, load = _Object$assign.load, loaded = _Object$assign.loaded; var observer = void 0; var mutationObserver = void 0; if (support('IntersectionObserver')) { observer = new IntersectionObserver(onIntersection(load, loaded), { root: root, rootMargin: rootMargin, threshold: threshold }); } if (support('MutationObserver') && enableAutoReload) { mutationObserver = new MutationObserver(onMutation(load, loaded)); } var elements = getElements(selector, root); for (var i = 0; i < elements.length; i++) { preLoad(elements[i]); } return { observe: function observe() { var elements = getElements(selector, root); for (var _i = 0; _i < elements.length; _i++) { if (isLoaded(elements[_i])) { continue; } if (observer) { if (mutationObserver && enableAutoReload) { mutationObserver.observe(elements[_i], { subtree: true, attributes: true, attributeFilter: validAttribute }); } observer.observe(elements[_i]); continue; } load(elements[_i]); markAsLoaded(elements[_i]); loaded(elements[_i]); } }, triggerLoad: function triggerLoad(element) { if (isLoaded(element)) { return; } load(element); markAsLoaded(element); loaded(element); }, observer: observer, mutationObserver: mutationObserver }; } return lozad; }))); ================================================ FILE: package.json ================================================ { "name": "lozad", "title": "lozad.js", "description": "A light-weight JS library to lazy load any HTML element such as images, ads, videos etc.", "version": "1.16.0", "homepage": "https://github.com/ApoorvSaxena/lozad.js", "license": "MIT", "scripts": { "test": "nyc mocha", "build": "rollup -c", "build:watch": "rollup -c -w -m inline", "prepublish": "npm run build", "prelint": "prettier --single-quote --no-semi --no-bracket-spacing --trailing-comma none --write \"lib/**/*.js\" --write build.js --write \"test/*.js\"", "precommit": "npm run lint && npm run build", "lint": "xo --fix src/*.js build.js test/*.js", "serve": "browser-sync start --server \"demo\" --server \".\" --files \"demo\" --files \"dist\" --port 3000", "dev": "run-p -r serve build:watch", "tag": "npm version minor --no-git-tag-version && npm run build && PACKAGE_VERSION=$(cat package.json | grep version | head -1 | awk -F: '{ print $2 }' | sed 's/[\",]//g' | tr -d '[[:space:]]') && git commit -am \"$PACKAGE_VERSION release\" && git tag v$PACKAGE_VERSION" }, "author": { "name": "Apoorv Saxena", "email": "root@apoorv.pro", "url": "https://apoorv.pro" }, "browser": "dist/lozad.es.js", "main": "dist/lozad.js", "module": "dist/lozad.es.js", "repository": { "type": "git", "url": "git://github.com/ApoorvSaxena/lozad.js.git" }, "bugs": { "url": "https://github.com/ApoorvSaxena/lozad.js/issues" }, "licenses": [ { "type": "MIT", "url": "https://github.com/ApoorvSaxena/lozad.js/blob/master/LICENSE" } ], "files": [ "dist/" ], "keywords": [ "lazy", "loader", "lazyloader", "lazyload", "performance", "image", "video", "iframe", "ads" ], "devDependencies": { "babel-core": "^6.26.0", "babel-preset-env": "^1.6.0", "babel-preset-stage-0": "^6.24.1", "browser-sync": "^3.0.4", "chokidar": "^3.1.1", "cross-env": "^5.2.1", "husky": "^0.14.3", "jsdom": "^27.0.0", "jsdom-global": "^3.0.2", "mocha": "^10.2.0", "npm-run-all": "^4.1.5", "nyc": "^14.1.1", "prettier": "^1.18.2", "rollup": "^4.50.1", "rollup-plugin-babel": "^3.0.2", "rollup-plugin-filesize": "^4.0.1", "rollup-plugin-license": "^3.0.1", "rollup-plugin-uglify": "^4.0.0", "xo": "^1.2.2" }, "xo": { "envs": [ "browser", "mocha" ], "semicolon": false, "space": true, "rules": { "unicorn/prefer-node-append": "off" } } } ================================================ FILE: rollup.config.js ================================================ import babel from 'rollup-plugin-babel'; import filesize from 'rollup-plugin-filesize'; import { uglify } from 'rollup-plugin-uglify'; import license from 'rollup-plugin-license'; import pkg from './package.json'; export default [ // browser-friendly UMD build { input: 'src/lozad.js', output: { name: pkg.name, file: pkg.main, format: 'umd' }, plugins: [ license({ banner: '/*! <%= pkg.title || pkg.name %> - v<%= pkg.version %> - ' + '<%= moment().format("YYYY-MM-DD") + "\\n" %>' + '<%= pkg.homepage ? "* " + pkg.homepage + "\\n" : "" %>' + '* Copyright (c) <%= moment().format("YYYY") %> <%= pkg.author.name %>;' + ' Licensed <%= _.map(pkg.licenses, "type").join(", ") %> */\n\n' }), babel({ babelrc: false, presets: [ [ 'env', { modules: false } ], 'stage-0' ] }), filesize() ] }, { input: 'src/lozad.js', output: { name: pkg.name, file: pkg.browser, format: 'umd' }, plugins: [ license({ banner: '/*! <%= pkg.title || pkg.name %> - v<%= pkg.version %> - ' + '<%= moment().format("YYYY-MM-DD") + "\\n" %>' + '<%= pkg.homepage ? "* " + pkg.homepage + "\\n" : "" %>' + '* Copyright (c) <%= moment().format("YYYY") %> <%= pkg.author.name %>;' + ' Licensed <%= _.map(pkg.licenses, "type").join(", ") %> */\n\n' }), babel({ babelrc: false, presets: [ [ 'env', { modules: false } ], 'stage-0' ] }), uglify({ output: { comments: true } }), filesize() ] }, // CommonJS (for Node) and ES module (for bundlers) build. // (We could have three entries in the configuration array // instead of two, but it's quicker to generate multiple // builds from a single configuration where possible, using // an array for the `output` option, where we can specify // `file` and `format` for each target) { input: 'src/lozad.js', output: [ // { file: pkg.main, format: 'cjs' }, { file: pkg.module, format: 'es' } ], plugins: [ license({ banner: '/*! <%= pkg.title || pkg.name %> - v<%= pkg.version %> - ' + '<%= moment().format("YYYY-MM-DD") + "\\n" %>' + '<%= pkg.homepage ? "* " + pkg.homepage + "\\n" : "" %>' + '* Copyright (c) <%= moment().format("YYYY") %> <%= pkg.author.name %>;' + ' Licensed <%= _.map(pkg.licenses, "type").join(", ") %> */\n\n' }), filesize() ] } ]; ================================================ FILE: src/lozad.js ================================================ /** * Detect IE browser * @const {boolean} * @private */ const isIE = typeof document !== 'undefined' && document.documentMode /** * * @param {string} type * */ const support = type => window && window[type] const validAttribute = ['data-iesrc', 'data-alt', 'data-src', 'data-srcset', 'data-background-image', 'data-toggle-class'] const defaultConfig = { rootMargin: '0px', threshold: 0, enableAutoReload: false, load(element) { if (element.nodeName.toLowerCase() === 'picture') { let img = element.querySelector('img') let append = false if (img === null) { img = document.createElement('img') append = true } if (isIE && element.getAttribute('data-iesrc')) { img.src = element.getAttribute('data-iesrc') } if (element.getAttribute('data-alt')) { img.alt = element.getAttribute('data-alt') } if (append) { element.append(img) } } if (element.nodeName.toLowerCase() === 'video' && !element.getAttribute('data-src')) { if (element.children) { const childs = element.children let childSrc for (let i = 0; i <= childs.length - 1; i++) { childSrc = childs[i].getAttribute('data-src') if (childSrc) { childs[i].src = childSrc } } element.load() } } if (element.getAttribute('data-poster')) { element.poster = element.getAttribute('data-poster') } if (element.getAttribute('data-src')) { element.src = element.getAttribute('data-src') } if (element.getAttribute('data-srcset')) { element.setAttribute('srcset', element.getAttribute('data-srcset')) } let backgroundImageDelimiter = ',' if (element.getAttribute('data-background-delimiter')) { backgroundImageDelimiter = element.getAttribute('data-background-delimiter') } if (element.getAttribute('data-background-image')) { element.style.backgroundImage = `url('${element.getAttribute('data-background-image').split(backgroundImageDelimiter).join('\'),url(\'')}')` } else if (element.getAttribute('data-background-image-set')) { const imageSetLinks = element.getAttribute('data-background-image-set').split(backgroundImageDelimiter) let firstUrlLink = (imageSetLinks[0].substr(0, imageSetLinks[0].indexOf(' ')) || imageSetLinks[0]) // Substring before ... 1x firstUrlLink = firstUrlLink.indexOf('url(') === -1 ? `url(${firstUrlLink})` : firstUrlLink if (imageSetLinks.length === 1) { element.style.backgroundImage = firstUrlLink } else { element.setAttribute('style', (element.getAttribute('style') || '') + `background-image: ${firstUrlLink}; background-image: -webkit-image-set(${imageSetLinks}); background-image: image-set(${imageSetLinks})`) } } if (element.getAttribute('data-toggle-class')) { element.classList.toggle(element.getAttribute('data-toggle-class')) } }, loaded() {} } function markAsLoaded(element) { element.setAttribute('data-loaded', true) } function preLoad(element) { if (element.getAttribute('data-placeholder-background')) { element.style.background = element.getAttribute('data-placeholder-background') } } const isLoaded = element => element.getAttribute('data-loaded') === 'true' const onIntersection = (load, loaded) => (entries, observer) => { entries.forEach(entry => { if (entry.intersectionRatio > 0 || entry.isIntersecting) { observer.unobserve(entry.target) if (!isLoaded(entry.target)) { load(entry.target) markAsLoaded(entry.target) loaded(entry.target) } } }) } const onMutation = load => entries => { entries.forEach(entry => { if (isLoaded(entry.target) && entry.type === 'attributes' && validAttribute.indexOf(entry.attributeName) > -1) { load(entry.target) } }) } const getElements = (selector, root = document) => { if (selector instanceof Element) { return [selector] } if (selector instanceof NodeList) { return selector } return root.querySelectorAll(selector) } export default function (selector = '.lozad', options = {}) { const {root, rootMargin, threshold, enableAutoReload, load, loaded} = Object.assign({}, defaultConfig, options) let observer let mutationObserver if (support('IntersectionObserver')) { observer = new IntersectionObserver(onIntersection(load, loaded), { root, rootMargin, threshold }) } if (support('MutationObserver') && enableAutoReload) { mutationObserver = new MutationObserver(onMutation(load, loaded)) } const elements = getElements(selector, root) for (let i = 0; i < elements.length; i++) { preLoad(elements[i]) } return { observe() { const elements = getElements(selector, root) for (let i = 0; i < elements.length; i++) { if (isLoaded(elements[i])) { continue } if (observer) { if (mutationObserver && enableAutoReload) { mutationObserver.observe(elements[i], {subtree: true, attributes: true, attributeFilter: validAttribute}) } observer.observe(elements[i]) continue } load(elements[i]) markAsLoaded(elements[i]) loaded(elements[i]) } }, triggerLoad(element) { if (isLoaded(element)) { return } load(element) markAsLoaded(element) loaded(element) }, observer, mutationObserver } } ================================================ FILE: test/index.js ================================================ require('jsdom-global')() const assert = require('assert') const lozad = require('../dist/lozad.js') describe('lozad', () => { describe('#lozad', () => { it('should be a function', () => { assert.strictEqual('function', typeof lozad) }) }) describe('#lozad return value', () => { it('should be an object', () => { const observer = lozad() assert.strictEqual('object', typeof observer) }) it('should expose observe API', () => { const observer = lozad() assert.strictEqual('function', typeof observer.observe) }) }) describe('images inside viewport without class lozad', () => { beforeEach(() => { document.body.innerHTML = '' const image = document.createElement('img') image.dataset.src = Math.random() .toString(36) .substring(7) document.body.appendChild(image) }) it('should not load image', () => { const observer = lozad() observer.observe() const image = document.querySelectorAll('img')[0] assert.strictEqual(undefined, image.dataset.loaded) }) }) describe('images inside viewport with class lozad', () => { beforeEach(() => { document.body.innerHTML = '' const image = document.createElement('img') image.dataset.src = Math.random() .toString(36) .substring(7) image.setAttribute('class', 'lozad') document.body.appendChild(image) }) it('should not load an image till observe function is called', () => { lozad() const image = document.querySelectorAll('img')[0] assert.strictEqual(undefined, image.dataset.loaded) }) it('should load an image after observe function is called', () => { const observer = lozad() const image = document.querySelectorAll('img')[0] observer.observe() assert.strictEqual('true', image.dataset.loaded) assert.strictEqual(image.getAttribute('src'), image.dataset.src) }) }) describe('images inside viewport with different class', () => { beforeEach(() => { document.body.innerHTML = '' const image = document.createElement('img') image.dataset.src = Math.random() .toString(36) .substring(7) document.body.appendChild(image) }) it('should load the image', () => { const className = 'test-class' const observer = lozad('.' + className) const image = document.querySelectorAll('img')[0] image.setAttribute('class', className) observer.observe() assert.strictEqual('true', image.dataset.loaded) assert.strictEqual(image.getAttribute('src'), image.dataset.src) }) }) describe('images inside viewport using a DOM `Element` reference', () => { beforeEach(() => { document.body.innerHTML = '' const image = document.createElement('img') image.dataset.src = Math.random() .toString(36) .substring(7) document.body.appendChild(image) }) it('should load the image', () => { const node = document.querySelector('img') const newSrc = Math.random() .toString(36) .substring(7) const observer = lozad(node) observer.observe() assert.strictEqual('true', node.dataset.loaded) assert.strictEqual(node.getAttribute('src'), node.dataset.src) node.dataset.src = newSrc setTimeout(() => { assert.notStrictEqual(node.getAttribute('src'), newSrc) }, 2000) }) it('should load the new image when sets enableAutoReload true and validating attributes changes', () => { const node = document.querySelector('img') const newSrc = Math.random() .toString(36) .substring(7) const observer = lozad(node, { enableAutoReload: true }) observer.observe() node.dataset.src = newSrc setTimeout(() => { assert.strictEqual(node.getAttribute('src'), newSrc) }, 2000) }) }) describe('images inside viewport using a DOM `NodeList` reference', () => { beforeEach(() => { document.body.innerHTML = '' const image = document.createElement('img') image.dataset.src = Math.random() .toString(36) .substring(7) document.body.appendChild(image) const imageTwo = document.createElement('img') imageTwo.dataset.src = Math.random() .toString(36) .substring(7) document.body.appendChild(imageTwo) }) it('should load the images', () => { const nodes = document.querySelectorAll('img') const observer = lozad(nodes) observer.observe() assert.strictEqual(nodes.length, 2) nodes.forEach(node => { assert.strictEqual('true', node.dataset.loaded) assert.strictEqual(node.getAttribute('src'), node.dataset.src) }) }) }) describe('images inside viewport with different attributes', () => { beforeEach(() => { document.body.innerHTML = '' const image = document.createElement('img') document.body.appendChild(image) }) it('should load the image with data-srcset attribute', () => { const dataSrcSetAttr = 'test-srcset' const observer = lozad() const image = document.querySelectorAll('img')[0] image.setAttribute('class', 'lozad') image.setAttribute('data-srcset', dataSrcSetAttr) observer.observe() assert.strictEqual('true', image.dataset.loaded) assert.strictEqual(image.getAttribute('srcset'), dataSrcSetAttr) }) it('should load the image with data-background-image attribute', () => { const bgImageAttr = 'test-bg-image' const observer = lozad() const image = document.querySelectorAll('img')[0] image.setAttribute('class', 'lozad') image.setAttribute('data-background-image', bgImageAttr) observer.observe() assert.strictEqual('true', image.dataset.loaded) assert.strictEqual( image.style.backgroundImage, 'url(' + bgImageAttr + ')' ) }) // Handle a single image src it('should load the image with data-background-image-set attribute', () => { const bgImageSetAttr = 'url("photo.jpg")' const observer = lozad() const image = document.querySelectorAll('img')[0] image.setAttribute('class', 'lozad') image.setAttribute('data-background-image-set', bgImageSetAttr) observer.observe() assert.strictEqual('true', image.dataset.loaded) assert.strictEqual( image.style.cssText, 'background-image: url(photo.jpg);' ) }) // Handle a single image set it('should load the image with data-background-image-set attribute', () => { const bgImageSetAttr = 'url("photo.jpg") 1x, url("photo@2x.jpg") 2x' const observer = lozad() const image = document.querySelectorAll('img')[0] image.setAttribute('class', 'lozad') image.style.background = 'white' image.setAttribute('data-background-image-set', bgImageSetAttr) observer.observe() assert.strictEqual('true', image.dataset.loaded) assert.strictEqual( image.getAttribute('style'), 'background: white;background-image: url("photo.jpg"); background-image: -webkit-image-set(url("photo.jpg") 1x, url("photo@2x.jpg") 2x); background-image: image-set(url("photo.jpg") 1x, url("photo@2x.jpg") 2x)' ) }) // Handle a single image set it('should load the image with data-background-image-set attribute', () => { const bgImageSetAttr = 'url("photo.jpg") 1x' const observer = lozad() const image = document.querySelectorAll('img')[0] image.setAttribute('class', 'lozad') image.setAttribute('data-background-image-set', bgImageSetAttr) observer.observe() assert.strictEqual('true', image.dataset.loaded) assert.strictEqual( image.style.cssText, 'background-image: url(photo.jpg);' ) }) // Handle image background placeholder it('should load the image with data-placeholder-background attribute', () => { const image = document.querySelectorAll('img')[0] const bgImageSetAttr = 'red' image.setAttribute('class', 'lozad') image.setAttribute('data-placeholder-background', bgImageSetAttr) const observer = lozad() observer.observe() assert.strictEqual('true', image.dataset.loaded) assert.strictEqual(image.style.cssText, 'background: red;') }) }) describe('when passing options', () => { beforeEach(() => { document.body.innerHTML = '' const image = document.createElement('img') image.dataset.src = Math.random() .toString(36) .substring(7) document.body.appendChild(image) }) it('should not load elements by default when custom load option is passed in', () => { const observer = lozad('.lozad', { load(element) { element.classList.add('loaded') } }) const image = document.querySelectorAll('img')[0] image.setAttribute('class', 'lozad') observer.observe() assert.strictEqual(true, image.classList.contains('loaded')) assert.strictEqual(null, image.getAttribute('src')) }) it('should run loaded option after loading an element', () => { const observer = lozad('.lozad', { loaded(element) { element.classList.add('loaded') } }) const image = document.querySelectorAll('img')[0] image.setAttribute('class', 'lozad') observer.observe() assert.strictEqual(true, image.classList.contains('loaded')) }) it('should set data attribute when loaded option is passed in', () => { const observer = lozad('.lozad', { loaded(element) { element.classList.add('loaded') } }) const image = document.querySelectorAll('img')[0] image.setAttribute('class', 'lozad') observer.observe() assert.strictEqual(true, image.classList.contains('loaded')) assert.strictEqual('true', image.dataset.loaded) }) }) describe('public API functions', () => { beforeEach(() => { document.body.innerHTML = '' const image = document.createElement('img') const src = Math.random() .toString(36) .substring(7) image.dataset.src = src document.body.appendChild(image) }) it('should load image via triggerLoad function', () => { const dataSrcSetAttr = 'test-srcset' const observer = lozad() const image = document.querySelectorAll('img')[0] image.setAttribute('class', 'lozad') image.setAttribute('data-srcset', dataSrcSetAttr) observer.triggerLoad(image) assert.strictEqual('true', image.dataset.loaded) assert.strictEqual(image.getAttribute('src'), image.dataset.src) }) }) describe('picture inside viewport with different class', () => { const src = Math.random() .toString(36) .substring(7) beforeEach(() => { document.body.innerHTML = '' const picture = document.createElement('picture') picture.setAttribute('data-alt', 'alt text') const source = document.createElement('source') source.setAttribute('srcset', src) picture.appendChild(source) document.body.appendChild(picture) }) it('should load the picture', () => { const className = 'test-class' const observer = lozad('.' + className) const picture = document.querySelectorAll('picture')[0] picture.setAttribute('class', className) observer.observe() assert.strictEqual('true', picture.dataset.loaded) }) it('should append image after last source', () => { const className = 'test-class' const observer = lozad('.' + className) const picture = document.querySelectorAll('picture')[0] picture.setAttribute('class', className) observer.observe() const img = picture.children[1] assert.strictEqual('IMG', img.tagName) }) it('should add alt attribute to image', () => { const className = 'test-class' const observer = lozad('.' + className) const picture = document.querySelectorAll('picture')[0] picture.setAttribute('class', className) observer.observe() const img = picture.children[1] assert.strictEqual('alt text', img.getAttribute('alt')) }) it('should use img tag if inside the picture', () => { const className = 'test-class' const observer = lozad('.' + className) const picture = document.querySelectorAll('picture')[0] picture.setAttribute('class', className) const initialImage = document.createElement('img') initialImage.setAttribute('customAttribute', 'custom value') picture.appendChild(initialImage) observer.observe() const img = picture.children[1] assert.strictEqual( initialImage.getAttribute('customAttribute'), img.getAttribute('customAttribute') ) }) }) describe('toggle class', () => { beforeEach(() => { document.body.innerHTML = '' const el = document.createElement('div') el.dataset.toggleClass = 'test' el.setAttribute('class', 'lozad') document.body.appendChild(el) }) it('should not toggle till observe function is called', () => { lozad() const el = document.querySelectorAll('div')[0] assert.strictEqual(false, el.classList.contains('test')) }) it('should toggle after observe function is called', () => { const observer = lozad() const el = document.querySelectorAll('div')[0] observer.observe() assert.strictEqual(true, el.classList.contains('test')) }) }) describe('video', () => { beforeEach(() => { document.body.innerHTML = '' const el = document.createElement('video') el.dataset.toggleClass = 'test' el.setAttribute('class', 'lozad') el.setAttribute('data-poster', 'test') document.body.appendChild(el) window.HTMLMediaElement.prototype.load = () => { /* Do nothing */ } }) it('should not toggle till observe function is called', () => { lozad() const el = document.querySelectorAll('video')[0] assert.strictEqual(false, el.classList.contains('test')) }) it('should toggle class and poster value after observe function is called', () => { const observer = lozad() const el = document.querySelectorAll('video')[0] observer.observe() assert.strictEqual(true, el.classList.contains('test')) assert.strictEqual(el.dataset.poster, el.poster) }) }) describe('exported IntersectionObserver and MutationObserver', () => { beforeEach(() => { document.body.innerHTML = '' const el = document.createElement('div') el.dataset.toggleClass = 'test' el.setAttribute('class', 'lozad') document.body.appendChild(el) }) it('should export the IntersectionObserver instance and MutationObserver instance', () => { const observer = lozad() assert.strictEqual(true, Object.keys(observer).includes('observer')) assert.strictEqual( true, Object.keys(observer).includes('mutationObserver') ) }) }) })