Home >Backend Development >PHP Problem >How to implement delayed loading of images in php
php method to implement delayed loading of images: when reaching the specified loading image location, replace the src attribute value of img with the data-src attribute value, such as [imgs[i].src = imgs[i ].getAttribute('data-src');】.
#When you reach the specified loading image location, just replace the attribute value of img's src with the attribute value of data-src. At this time, img will request resource.
(Recommended tutorial: php video tutorial)
imgs[i].src = imgs[i].getAttribute('data-src');
Code implementation:
图片懒加载 <script> var imgs = document.querySelectorAll('img'); //offsetTop是元素与offsetParent的距离,循环获取直到页面顶部 function getTop(e) { var T = e.offsetTop; while(e = e.offsetParent) { T += e.offsetTop; } return T; } function lazyLoad(imgs) { var H = document.documentElement.clientHeight;//获取可视区域高度 var S = document.documentElement.scrollTop || document.body.scrollTop; for (var i = 0; i < imgs.length; i++) { if (H + S > getTop(imgs[i])) { imgs[i].src = imgs[i].getAttribute(&#39;data-src&#39;); } } } window.onload = window.onscroll = function () { //onscroll()在滚动条滚动的时候触发 lazyLoad(imgs); } </script>
Related recommendations: php training
The above is the detailed content of How to implement delayed loading of images in php. For more information, please follow other related articles on the PHP Chinese website!