UNPKG

loading-attribute-polyfill

Version:

Fast and lightweight dependency-free vanilla JavaScript polyfill for native lazy loading / the awesome loading='lazy'-attribute.

3 lines (2 loc) 2.54 kB
const e="loading"in HTMLImageElement.prototype,t="loading"in HTMLIFrameElement.prototype,r="onscroll"in window;let a;function o(e){let t=[];"picture"===e.parentNode.tagName.toLowerCase()&&(function(e){const t=e.querySelector("source[data-lazy-remove]");t&&e.removeChild(t)}(e.parentNode),t=Array.prototype.slice.call(e.parentNode.querySelectorAll("source"))),t.push(e),t.forEach(e=>{e.hasAttribute("data-lazy-srcset")&&(e.setAttribute("srcset",e.getAttribute("data-lazy-srcset")),e.removeAttribute("data-lazy-srcset"))}),e.setAttribute("src",e.getAttribute("data-lazy-src")),e.removeAttribute("data-lazy-src")}function n(o){const n=document.createElement("div");for(n.innerHTML=function(o){let n=o.textContent||o.innerHTML;const c="data:image/svg+xml,%3Csvg xmlns=%27http://www.w3.org/2000/svg%27 viewBox=%270 0 "+((n.match(/width=['"](\d+)['"]/)||!1)[1]||1)+" "+((n.match(/height=['"](\d+)['"]/)||!1)[1]||1)+"%27%3E%3C/svg%3E";return(/<img/gim.test(n)&&!e||/<iframe/gim.test(n)&&!t)&&r&&(void 0===a?n=n.replace(/(?:\r\n|\r|\n|\t| )src=/g,' lazyload="1" src='):(n=n.replace("<source",'<source srcset="'+c+'" data-lazy-remove="true"></source>\n<source'),n=n.replace(/(?:\r\n|\r|\n|\t| )srcset=/g," data-lazy-srcset=").replace(/(?:\r\n|\r|\n|\t| )src=/g,' src="'+c+'" data-lazy-src='))),n}(o);n.firstChild;){const c=n.firstChild;if(r&&void 0!==a&&c.tagName&&(("img"===c.tagName.toLowerCase()||"picture"===c.tagName.toLowerCase())&&!e||"iframe"===c.tagName.toLowerCase()&&!t)){const e="picture"===c.tagName.toLowerCase()?n.querySelector("img"):c;a.observe(e)}o.parentNode.insertBefore(c,o)}o.parentNode.removeChild(o)}window.NodeList&&!NodeList.prototype.forEach&&(NodeList.prototype.forEach=Array.prototype.forEach),"IntersectionObserver"in window&&(a=new IntersectionObserver(function(e,t){e.forEach(e=>{if(0===e.intersectionRatio)return;const r=e.target;t.unobserve(r),o(r)})},{rootMargin:"0px 0px 256px 0px",threshold:.01}));const c=()=>{document.querySelectorAll("noscript.loading-lazy").forEach(e=>n(e)),void 0!==window.matchMedia&&window.matchMedia("print").addListener(e=>{e.matches&&document.querySelectorAll('img[loading="lazy"][data-lazy-src],iframe[loading="lazy"][data-lazy-src]').forEach(e=>{o(e)})})};/comp|inter/.test(document.readyState)?c():"addEventListener"in document?document.addEventListener("DOMContentLoaded",()=>{c()}):document.attachEvent("onreadystatechange",()=>{"complete"===document.readyState&&c()});const s={prepareElement:n};export{s as default}; //# sourceMappingURL=loading-attribute-polyfill.modern.js.map