├── .gitignore ├── .jshintrc ├── .travis.yml ├── LICENSE.md ├── Makefile ├── README.md ├── lazyload.js ├── lazyload.min.js ├── lazyload.min.js.map └── package.json /.gitignore: -------------------------------------------------------------------------------- 1 | yarn-error.log 2 | yarn.lock 3 | node_modules -------------------------------------------------------------------------------- /.jshintrc: -------------------------------------------------------------------------------- 1 | { 2 | "esversion": 6, 3 | "curly": true, 4 | "eqeqeq": true, 5 | "eqnull": true, 6 | "immed": true, 7 | "noarg": true, 8 | "quotmark": "double", 9 | "trailing": true, 10 | "undef": true, 11 | "unused": "vars", 12 | 13 | "node": true, 14 | "jquery": true, 15 | "browser": true, 16 | 17 | "predef": [ 18 | "define", 19 | "IntersectionObserver" 20 | ] 21 | } -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | sudo: false 2 | 3 | language: node_js 4 | 5 | node_js: 6 | - "7" 7 | 8 | install: 9 | - npm install 10 | 11 | script: 12 | - make travis 13 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | ===================== 3 | 4 | Copyright (c) 2007-2019 Mika Tuupola 5 | 6 | Permission is hereby granted, free of charge, to any person obtaining a copy 7 | of this software and associated documentation files (the "Software"), to deal 8 | in the Software without restriction, including without limitation the rights 9 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | copies of the Software, and to permit persons to whom the Software is 11 | furnished to do so, subject to the following conditions: 12 | 13 | The above copyright notice and this permission notice shall be included in 14 | all copies or substantial portions of the Software. 15 | 16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | THE SOFTWARE. 23 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | .DEFAULT_GOAL := help 2 | 3 | help: 4 | @echo "" 5 | @echo "Available tasks:" 6 | @echo " lint Run linter and code style checker" 7 | @echo " unit Run unit tests and generate coverage" 8 | @echo " test Run linter and unit tests" 9 | @echo " watch Run linter and unit tests when any of the source files change" 10 | @echo " deps Install dependencies" 11 | @echo " build Build minified version" 12 | @echo " all Install dependencies and run linter and unit tests" 13 | @echo "" 14 | 15 | deps: 16 | yarn install 17 | 18 | lint: 19 | node_modules/.bin/jshint lazyload.js 20 | 21 | unit: 22 | @echo "No unit tests." 23 | 24 | watch: 25 | find . -name "*.js" -not -path "./node_modules/*" -o -name "*.json" -not -path "./node_modules/*" | entr -c make test 26 | 27 | test: lint unit 28 | 29 | travis: lint unit 30 | 31 | build: 32 | node_modules/.bin/uglifyjs lazyload.js --compress --mangle --source-map --output lazyload.min.js 33 | sed -i "1s/^/\/*! Lazy Load 2.0.0-rc.2 - MIT license - Copyright 2007-2019 Mika Tuupola *\/\n/" lazyload.min.js 34 | 35 | all: deps test build 36 | 37 | .PHONY: help deps lint test watch build all 38 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Lazy Load Remastered 2 | 3 | Lazy Load delays loading of images in long web pages. Images outside of viewport will not be loaded before user scrolls to them. This is opposite of image preloading. 4 | 5 | This is a modern vanilla JavaScript version of the original [Lazy Load](https://github.com/tuupola/jquery_lazyload) plugin. It uses [Intersection Observer API](https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API) to observe when the image enters the browsers viewport. Original code was inspired by [YUI ImageLoader](https://yuilibrary.com/yui/docs/imageloader/) utility by Matt Mlinac. New version loans heavily from a [blog post](https://deanhume.com/Home/BlogPost/lazy-loading-images-using-intersection-observer/10163) by Dean Hume. 6 | 7 | ## Basic Usage 8 | 9 | By default Lazy Load assumes the URL of the original high resolution image can be found in `data-src` attribute. You can also include an optional low resolution placeholder in the `src` attribute. 10 | 11 | ```html 12 | 13 | 14 | 15 | 16 | ``` 17 | 18 | With the HTML in place you can then initialize the plugin using the factory method. If you do not pass any settings or image elements it will lazyload all images with class `lazyload`. 19 | 20 | ```js 21 | lazyload(); 22 | ``` 23 | 24 | If you prefer you can explicitly pass the image elements to the factory. Use this for example if you use different class name. 25 | 26 | ```js 27 | let images = document.querySelectorAll(".branwdo"); 28 | lazyload(images); 29 | ``` 30 | 31 | If you prefer you can also use the plain old constructor. 32 | 33 | ```js 34 | let images = document.querySelectorAll(".branwdo"); 35 | new LazyLoad(images); 36 | ``` 37 | 38 | The core IntersectionObserver can be configured by passing an additional argument 39 | 40 | ```js 41 | new LazyLoad(images, { 42 | root: null, 43 | rootMargin: "0px", 44 | threshold: 0 45 | }); 46 | ``` 47 | 48 | ## Additional API 49 | 50 | To use the additional API you need to assign the plugin instance to a variable. 51 | 52 | ```js 53 | let lazy = lazyload(); 54 | ``` 55 | 56 | To force loading of all images use `loadimages()`. 57 | 58 | ```js 59 | lazy->loadImages(); 60 | ``` 61 | 62 | To destroy the plugin and stop lazyloading use `destroy()`. 63 | 64 | ```js 65 | lazy->destroy(); 66 | ``` 67 | 68 | Note that `destroy()` does not load the out of viewport images. If you also 69 | want to load the images use `loadAndDestroy()`. 70 | 71 | ```js 72 | lazy->loadAndDestroy(); 73 | ``` 74 | 75 | Additional API is not avalaible with the jQuery wrapper. 76 | 77 | ## jQuery Wrapper 78 | 79 | If you use jQuery there is a wrapper which you can use with the familiar old syntax. Note that to provide BC it uses `data-original` by default. This should be a drop in replacement for the previous version of the plugin. 80 | 81 | ```html 82 | 83 | 84 | ``` 85 | 86 | ```js 87 | $("img.lazyload").lazyload(); 88 | ``` 89 | 90 | ## Cookbook 91 | 92 | ### Blur Up Images 93 | 94 | Low resolution placeholder ie. the "blur up" technique. You can see this in action [in this blog entry](https://appelsiini.net/2017/trilateration-with-n-points/). Scroll down to see blur up images. 95 | 96 | ```html 97 | 101 | ``` 102 | 103 | ```html 104 |
107 | ``` 108 | 109 | ### Responsive Images 110 | 111 | Lazyloaded [Responsive images](https://www.smashingmagazine.com/2014/05/responsive-images-done-right-guide-picture-srcset/) are supported via `data-srcset`. If browser does not support `srcset` and there is no polyfill the image from `data-src` will be shown. 112 | 113 | ```html 114 | 119 | ``` 120 | 121 | ```html 122 | 127 | ``` 128 | 129 | 130 | ### Inlined Placeholder Image 131 | 132 | To reduce the amount of request you can use data uri images as the placeholder. 133 | 134 | ```html 135 | 138 | ``` 139 | 140 | ## Install 141 | 142 | This is still work in progress. You can install beta version with yarn or npm. 143 | 144 | ``` 145 | $ yarn add lazyload 146 | $ npm install lazyload 147 | ``` 148 | 149 | # License 150 | 151 | All code licensed under the [MIT License](http://www.opensource.org/licenses/mit-license.php). All images licensed under [Creative Commons Attribution 3.0 Unported License](http://creativecommons.org/licenses/by/3.0/deed.en_US). In other words you are basically free to do whatever you want. Just don't remove my name from the source. 152 | 153 | -------------------------------------------------------------------------------- /lazyload.js: -------------------------------------------------------------------------------- 1 | /*! 2 | * Lazy Load - JavaScript plugin for lazy loading images 3 | * 4 | * Copyright (c) 2007-2019 Mika Tuupola 5 | * 6 | * Licensed under the MIT license: 7 | * http://www.opensource.org/licenses/mit-license.php 8 | * 9 | * Project home: 10 | * https://appelsiini.net/projects/lazyload 11 | * 12 | * Version: 2.0.0-rc.2 13 | * 14 | */ 15 | 16 | (function (root, factory) { 17 | if (typeof exports === "object") { 18 | module.exports = factory(root); 19 | } else if (typeof define === "function" && define.amd) { 20 | define([], factory); 21 | } else { 22 | root.LazyLoad = factory(root); 23 | } 24 | }) (typeof global !== "undefined" ? global : this.window || this.global, function (root) { 25 | 26 | "use strict"; 27 | 28 | if (typeof define === "function" && define.amd){ 29 | root = window; 30 | } 31 | 32 | const defaults = { 33 | src: "data-src", 34 | srcset: "data-srcset", 35 | selector: ".lazyload", 36 | root: null, 37 | rootMargin: "0px", 38 | threshold: 0 39 | }; 40 | 41 | /** 42 | * Merge two or more objects. Returns a new object. 43 | * @private 44 | * @param {Boolean} deep If true, do a deep (or recursive) merge [optional] 45 | * @param {Object} objects The objects to merge together 46 | * @returns {Object} Merged values of defaults and options 47 | */ 48 | const extend = function () { 49 | 50 | let extended = {}; 51 | let deep = false; 52 | let i = 0; 53 | let length = arguments.length; 54 | 55 | /* Check if a deep merge */ 56 | if (Object.prototype.toString.call(arguments[0]) === "[object Boolean]") { 57 | deep = arguments[0]; 58 | i++; 59 | } 60 | 61 | /* Merge the object into the extended object */ 62 | let merge = function (obj) { 63 | for (let prop in obj) { 64 | if (Object.prototype.hasOwnProperty.call(obj, prop)) { 65 | /* If deep merge and property is an object, merge properties */ 66 | if (deep && Object.prototype.toString.call(obj[prop]) === "[object Object]") { 67 | extended[prop] = extend(true, extended[prop], obj[prop]); 68 | } else { 69 | extended[prop] = obj[prop]; 70 | } 71 | } 72 | } 73 | }; 74 | 75 | /* Loop through each object and conduct a merge */ 76 | for (; i < length; i++) { 77 | let obj = arguments[i]; 78 | merge(obj); 79 | } 80 | 81 | return extended; 82 | }; 83 | 84 | function LazyLoad(images, options) { 85 | this.settings = extend(defaults, options || {}); 86 | this.images = images || document.querySelectorAll(this.settings.selector); 87 | this.observer = null; 88 | this.init(); 89 | } 90 | 91 | LazyLoad.prototype = { 92 | init: function() { 93 | 94 | /* Without observers load everything and bail out early. */ 95 | if (!root.IntersectionObserver) { 96 | this.loadImages(); 97 | return; 98 | } 99 | 100 | let self = this; 101 | let observerConfig = { 102 | root: this.settings.root, 103 | rootMargin: this.settings.rootMargin, 104 | threshold: [this.settings.threshold] 105 | }; 106 | 107 | this.observer = new IntersectionObserver(function(entries) { 108 | Array.prototype.forEach.call(entries, function (entry) { 109 | if (entry.isIntersecting) { 110 | self.observer.unobserve(entry.target); 111 | let src = entry.target.getAttribute(self.settings.src); 112 | let srcset = entry.target.getAttribute(self.settings.srcset); 113 | if ("img" === entry.target.tagName.toLowerCase()) { 114 | if (src) { 115 | entry.target.src = src; 116 | } 117 | if (srcset) { 118 | entry.target.srcset = srcset; 119 | } 120 | } else { 121 | entry.target.style.backgroundImage = "url(" + src + ")"; 122 | } 123 | } 124 | }); 125 | }, observerConfig); 126 | 127 | Array.prototype.forEach.call(this.images, function (image) { 128 | self.observer.observe(image); 129 | }); 130 | }, 131 | 132 | loadAndDestroy: function () { 133 | if (!this.settings) { return; } 134 | this.loadImages(); 135 | this.destroy(); 136 | }, 137 | 138 | loadImages: function () { 139 | if (!this.settings) { return; } 140 | 141 | let self = this; 142 | Array.prototype.forEach.call(this.images, function (image) { 143 | let src = image.getAttribute(self.settings.src); 144 | let srcset = image.getAttribute(self.settings.srcset); 145 | if ("img" === image.tagName.toLowerCase()) { 146 | if (src) { 147 | image.src = src; 148 | } 149 | if (srcset) { 150 | image.srcset = srcset; 151 | } 152 | } else { 153 | image.style.backgroundImage = "url('" + src + "')"; 154 | } 155 | }); 156 | }, 157 | 158 | destroy: function () { 159 | if (!this.settings) { return; } 160 | this.observer.disconnect(); 161 | this.settings = null; 162 | } 163 | }; 164 | 165 | root.lazyload = function(images, options) { 166 | return new LazyLoad(images, options); 167 | }; 168 | 169 | if (root.jQuery) { 170 | const $ = root.jQuery; 171 | $.fn.lazyload = function (options) { 172 | options = options || {}; 173 | options.attribute = options.attribute || "data-src"; 174 | new LazyLoad($.makeArray(this), options); 175 | return this; 176 | }; 177 | } 178 | 179 | return LazyLoad; 180 | }); 181 | -------------------------------------------------------------------------------- /lazyload.min.js: -------------------------------------------------------------------------------- 1 | /*! Lazy Load 2.0.0-rc.2 - MIT license - Copyright 2007-2019 Mika Tuupola */ 2 | !function(t,e){"object"==typeof exports?module.exports=e(t):"function"==typeof define&&define.amd?define([],e):t.LazyLoad=e(t)}("undefined"!=typeof global?global:this.window||this.global,function(t){"use strict";function e(t,e){this.settings=s(r,e||{}),this.images=t||document.querySelectorAll(this.settings.selector),this.observer=null,this.init()}"function"==typeof define&&define.amd&&(t=window);const r={src:"data-src",srcset:"data-srcset",selector:".lazyload",root:null,rootMargin:"0px",threshold:0},s=function(){let t={},e=!1,r=0,o=arguments.length;"[object Boolean]"===Object.prototype.toString.call(arguments[0])&&(e=arguments[0],r++);for(;r", 8 | "license": "MIT", 9 | "keywords": [ 10 | "lazyload" 11 | ], 12 | "files": [ 13 | "lazyload.js", 14 | "lazyload.min.js" 15 | ], 16 | "devDependencies": { 17 | "jshint": "^2.9.5", 18 | "uglify-es": "^3.0.28" 19 | } 20 | } 21 | --------------------------------------------------------------------------------