简体   繁体   English

如何对ES5中从服务器返回的图像实施延迟加载?

[英]How to implement lazy load for images returned from a server in ES5?

On one page, I'm trying to lazy load potentially hundreds of images that are returned from my server as blobs. 在一页上,我试图延迟加载可能数百个从服务器作为blob返回的图像。 I've tried converting them to base64 data uris then using some lazy loading techniques, but understandably that didn't work, since the data uri is already in the html, which means the browser still needs to load the image data even if it's not going to display it right away. 我曾尝试将它们转换为base64数据uri,然后使用一些延迟加载技术,但可以理解的是这没有用,因为数据uri已经在html中,这意味着浏览器仍然需要加载图像数据,即使它不是马上显示出来。

Is there some way to lazy load dynamic images returned by a server as blobs? 有什么方法可以延迟加载服务器返回的动态图像作为Blob? Or some way to convert them to use remote image urls then use typical lazy loading that way? 还是通过某种方式将它们转换为使用远程图像url,然后以这种方式使用典型的延迟加载?

Thanks for any help. 谢谢你的帮助。

ES5 approach : XMLHttpRequest ES5方法:XMLHttpRequest

In this scenario you get an arraybuffer from the ajax request, that must be converted into a base64 string, before being useful. 在这种情况下,您将从ajax请求中获得一个arraybuffer ,在使用前必须将其转换为base64字符串。 (IE10+ Compatible Method) (IE10 +兼容方法)

 let myImg = document.getElementById('myImg'); let url = "https://placekitten.com/200/300"; let request = new XMLHttpRequest(); request.open ("GET", url, true); request.responseType = "arraybuffer"; request.send (null); request.onreadystatechange= function(response){ if (request.readyState === 4) { if (request.status === 200) { // convert received arrayBuffer into base64 encoded string var imgBase64 = btoa(String.fromCharCode.apply(null, new Uint8Array(request.response))); // assign base64 encoded image to image source myImg.src= 'data:image/jpeg;base64,' + imgBase64; } } } 
 <img id="myImg" /> 

Note: CORS must be taken in consideration, when retrieving images from external domains. 注意:从外部域检索图像时,必须考虑CORS。


ES6 approach : Fetch ES6方法:提取

You can use fetch to retrieve your images, and inject them in the DOM as soon as you receive them... 您可以使用fetch来检索图像,并在收到图像后立即将它们注入DOM中。

 let myImage = document.getElementById('myImg'); let url = "https://placekitten.com/200/300"; fetch(url) .then( response=> { // if response is OK, covert it into a blob if(response.ok) return response.blob(); else throw new Error('Response not OK'); }) .then(myBlob=>{ // Assign it to the image src using createObjectURL myImage.src = URL.createObjectURL(myBlob); }) .catch(function(error){ // hadle errors console.log(error.message); }); 
 <img id="myImg" /> 

You can get more details about Fetch and createObjectURL in the Mozilla Developer webpage. 您可以在Mozilla开发人员网页上获取有关FetchcreateObjectURL的更多详细信息。


Previous code can be easily converted into reusable functions, suitable for generic scenarios. 先前的代码可以轻松转换为可重用的函数,适用于一般情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM