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
var e,t="loading"in HTMLImageElement.prototype,r="loading"in HTMLIFrameElement.prototype,a="onscroll"in window;function o(e){var t,r,a=[];"picture"===e.parentNode.tagName.toLowerCase()&&((r=(t=e.parentNode).querySelector("source[data-lazy-remove]"))&&t.removeChild(r),a=Array.prototype.slice.call(e.parentNode.querySelectorAll("source"))),a.push(e),a.forEach(function(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){var n=document.createElement("div");for(n.innerHTML=function(o){var n=o.textContent||o.innerHTML,i="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)&&!t||/<iframe/gim.test(n)&&!r)&&a&&(n=void 0===e?n.replace(/(?:\r\n|\r|\n|\t| )src=/g,' lazyload="1" src='):(n=n.replace("<source",'<source srcset="'+i+'" data-lazy-remove="true"></source>\n<source')).replace(/(?:\r\n|\r|\n|\t| )srcset=/g," data-lazy-srcset=").replace(/(?:\r\n|\r|\n|\t| )src=/g,' src="'+i+'" data-lazy-src=')),n}(o);n.firstChild;){var i=n.firstChild;if(a&&void 0!==e&&i.tagName&&(("img"===i.tagName.toLowerCase()||"picture"===i.tagName.toLowerCase())&&!t||"iframe"===i.tagName.toLowerCase()&&!r)){var c="picture"===i.tagName.toLowerCase()?n.querySelector("img"):i;e.observe(c)}o.parentNode.insertBefore(i,o)}o.parentNode.removeChild(o)}window.NodeList&&!NodeList.prototype.forEach&&(NodeList.prototype.forEach=Array.prototype.forEach),"IntersectionObserver"in window&&(e=new IntersectionObserver(function(e,t){e.forEach(function(e){if(0!==e.intersectionRatio){var r=e.target;t.unobserve(r),o(r)}})},{rootMargin:"0px 0px 256px 0px",threshold:.01}));var i=function(){document.querySelectorAll("noscript.loading-lazy").forEach(function(e){return n(e)}),void 0!==window.matchMedia&&window.matchMedia("print").addListener(function(e){e.matches&&document.querySelectorAll('img[loading="lazy"][data-lazy-src],iframe[loading="lazy"][data-lazy-src]').forEach(function(e){o(e)})})};/comp|inter/.test(document.readyState)?i():"addEventListener"in document?document.addEventListener("DOMContentLoaded",function(){i()}):document.attachEvent("onreadystatechange",function(){"complete"===document.readyState&&i()}),module.exports={prepareElement:n}; //# sourceMappingURL=loading-attribute-polyfill.js.map