├── .gitignore ├── prettier.config.js ├── test ├── .eslintrc.json ├── karma.config.js └── test.js ├── .travis.yml ├── .eslintrc.json ├── package.json ├── LICENSE ├── index.js ├── README.md └── examples └── index.html /.gitignore: -------------------------------------------------------------------------------- 1 | dist 2 | node_modules 3 | -------------------------------------------------------------------------------- /prettier.config.js: -------------------------------------------------------------------------------- 1 | /* @flow strict */ 2 | module.exports = require('eslint-plugin-github/prettier.config') 3 | -------------------------------------------------------------------------------- /test/.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "env": { 3 | "mocha": true 4 | }, 5 | "globals": { 6 | "assert": true 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | sudo: required 3 | node_js: 4 | - "node" 5 | addons: 6 | chrome: stable 7 | cache: 8 | directories: 9 | - node_modules 10 | -------------------------------------------------------------------------------- /.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": [ 3 | "plugin:github/browser", 4 | "plugin:github/es6", 5 | "plugin:github/flow" 6 | ], 7 | "parser": "babel-eslint", 8 | "overrides": [ 9 | { 10 | "files": "test/**/*.js", 11 | "rules": { 12 | "flowtype/require-valid-file-annotation": "off", 13 | "github/unescaped-html-literal": "off" 14 | } 15 | } 16 | ] 17 | } 18 | -------------------------------------------------------------------------------- /test/karma.config.js: -------------------------------------------------------------------------------- 1 | module.exports = function(config) { 2 | config.set({ 3 | frameworks: ['mocha', 'chai'], 4 | files: ['../dist/index.umd.js', 'test.js'], 5 | reporters: ['mocha'], 6 | port: 9876, 7 | colors: true, 8 | logLevel: config.LOG_INFO, 9 | browsers: ['ChromeHeadless'], 10 | autoWatch: false, 11 | singleRun: true, 12 | concurrency: Infinity 13 | }) 14 | } 15 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "lazy-loadable", 3 | "version": "0.1.3", 4 | "description": "Boilerplate for creating lazy-loadable images.", 5 | "type": "module", 6 | "main": "index.js", 7 | "module": "index.js", 8 | "license": "MIT", 9 | "repository": { 10 | "type": "git", 11 | "url": "git+https://github.com/manobi/lazy-loadable.git" 12 | }, 13 | "files": [ 14 | "index.js", 15 | "package.json", 16 | "README.md" 17 | ] 18 | } 19 | -------------------------------------------------------------------------------- /test/test.js: -------------------------------------------------------------------------------- 1 | describe('custom-element', function() { 2 | describe('element creation', function() { 3 | it('creates from document.createElement', function() { 4 | const el = document.createElement('custom-element') 5 | assert.equal('CUSTOM-ELEMENT', el.nodeName) 6 | }) 7 | 8 | it('creates from constructor', function() { 9 | const el = new window.CustomElementElement() 10 | assert.equal('CUSTOM-ELEMENT', el.nodeName) 11 | }) 12 | }) 13 | 14 | describe('after tree insertion', function() { 15 | beforeEach(function() { 16 | document.body.innerHTML = '' 17 | }) 18 | 19 | afterEach(function() { 20 | document.body.innerHTML = '' 21 | }) 22 | 23 | it('initiates', function() { 24 | const ce = document.querySelector('custom-element') 25 | assert.equal(ce.textContent, ':wave:') 26 | }) 27 | }) 28 | }) 29 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2019 Manobi. 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining 4 | a copy of this software and associated documentation files (the 5 | "Software"), to deal in the Software without restriction, including 6 | without limitation the rights to use, copy, modify, merge, publish, 7 | distribute, sublicense, and/or sell copies of the Software, and to 8 | permit persons to whom the Software is furnished to do so, subject to 9 | the following conditions: 10 | 11 | The above copyright notice and this permission notice shall be 12 | included in all copies or substantial portions of the Software. 13 | 14 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 15 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 16 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 17 | NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 18 | LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 19 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 20 | WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 21 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | const opts = { 2 | root: null, 3 | rootMargin: "0px", 4 | threshold: [0] 5 | } 6 | 7 | function prefetch(url) { 8 | return fetch(url, {credentials: `include`, cache: 'force-cache'}).then(async res => await res.blob()) 9 | } 10 | 11 | function loadSrc(target, io){ 12 | target.removeAttribute('srcset'); 13 | io.unobserve(target); 14 | } 15 | 16 | const io = new IntersectionObserver((entries) => { 17 | entries.forEach(({isIntersecting, target}) => { 18 | if(isIntersecting){ 19 | loadSrc(target, io); 20 | const link = target.getAttribute('link'); 21 | if(link){ 22 | target.addEventListener('load', () => prefetch(link), {once: true}); 23 | } 24 | } 25 | }) 26 | }, opts); 27 | 28 | export default class LazyLoadable extends HTMLImageElement { 29 | constructor(width, height){ 30 | super(width, height); 31 | } 32 | 33 | get loading(){ 34 | return this.getAttribute('loading') 35 | } 36 | 37 | get isModern(){ 38 | return ('loading' in HTMLImageElement.prototype) 39 | } 40 | 41 | connectedCallback(){ 42 | if(this.loading === 'lazy'){ 43 | return io.observe(this); 44 | } 45 | // default behaviour is to eagerly load the image 46 | loadSrc(this, io); 47 | } 48 | 49 | disconnectedCallback(){ 50 | io.unobserve(this); 51 | } 52 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Native lazy load boilerplate 2 | 3 | * 🧱 Pollyfill for modern browsers 4 | * 👵 Gracefully degrades for old browsers 5 | * 🤖 Future proof markup 6 | * 🚉 Using the platform 7 | 8 | The whole idea is to create a copy-past boilerplate that works today. If by a miracle all browser vendors agree to ship "native lazy load", you would **only have to change one place**. 9 | 10 | 11 | ## Boilerplate 12 | ```html 13 | 24 | 28 | ``` 29 | 30 | ## Attributes breakdown 31 | 32 | ***is="lazy-loadable"*** 33 | 34 | Apply the lazy-loadable custom element pollyfill behaviour to your image tag. 35 | Usually people loop over all images on a page (querySelectorAll('img.lazy').forEach), to decide if it should lazy load, it can be very slow, you also have to wait until the DOM is ready or put your script at end of body, it would not work if a image appears in document after the document have loaded, like in infinity scrolling or lazy rendering. Using custom elements the browser handles all of it for you. 36 | 37 | ***loading="lazy"*** 38 | 39 | The native way to tell the browser to delay the image loading, until it's in the screen. Only Google Chrome have [shipped it yet](https://caniuse.com/#feat=loading-lazy-attr). 40 | 41 | ***lazyload="1"*** 42 | 43 | It seems [Microsoft](https://msdn.microsoft.com/en-us/ie/dn369270(v=vs.94)) implemented on IE 11 and Edge 12 a [unofficial attribute](https://caniuse.com/#feat=lazyload) called "lazyload". 44 | But it does not work the same way as "loading=lazy", it only tell the browser to decrese the loading priority of the resource. Actually it's pretty similar to what "importance=low" does. 45 | 46 | ***importance="low"*** 47 | 48 | This is a [spec proposal](https://wicg.github.io/priority-hints/) to enable developers to signal the priority of each resource they need to download. In case a browser vendor never implement the "native lazy load", but for any reason ships the **priority hints** support, we would at least download the image without high priority. 49 | 50 | ***srcset*** 51 | Since there is no ways yet to know [if the browser have native support](https://bugs.chromium.org/p/chromium/issues/detail?id=949365) before images starts loading we need to set a placeholder image. 52 | 53 | Our placeholder is the one responsible for the magic. I've chosen to use srcset as placeholder instead of a infamous "data-src". By placing the placeholder on "srcattr", we can hold the "src" loading, until we are sure if the browser handles lazy by default. In future if all browsers support native lazy-load, all you would have to do is remove this attribute from your html. 54 | 55 | The great advantage of using "srcattr" instead of "data-src" is that when you remove the placeholder, browsers already knows what to do, respecting the standard fallback src, picture source, media attributes and pixel density. 56 | 57 | ***width & height*** 58 | Explicitally declare the image size to avoid page jumps. 59 | 60 | ## Safari custom elements pollyfill 61 | 62 | Apple have chosen [to not ship](https://github.com/w3c/webcomponents/issues/509) a complete implementation of custom elements V1, in order for it to work in Safari you may have to use the [ungap pollyfill](https://github.com/ungap/custom-elements-builtin) before your scripts: 63 | 64 | ```html 65 | 72 | ```` 73 | 74 | ## Install 75 | If you prefer to bundle the pollyfill yourself or use it with a framework: 76 | 77 | ```shell 78 | npm install lazy-loadable -s 79 | ``` 80 | 81 | ```javascript 82 | import LazyLoadable from 'lazy-loadable'; 83 | customElements.define('lazy-loadable', LazyLoadable, { extends: "img" }); 84 | ``` 85 | 86 | ## License 87 | 88 | Distributed under the MIT license. See LICENSE for details. 89 | -------------------------------------------------------------------------------- /examples/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | LazyLoadable Custom element 6 | 7 | 8 | 18 | 19 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 145 | 149 | 150 | 151 | --------------------------------------------------------------------------------