gpt4 book ai didi

javascript - 使用ajax预加载图像

转载 作者:数据小太阳 更新时间:2023-10-29 05:23:41 24 4
gpt4 key购买 nike

在以下位置找到了使用 ajax 预加载内容的技术:http://perishablepress.com/3-ways-preload-images-css-javascript-ajax/

window.onload = function() {
setTimeout(function() {
// XHR to request a JS and a CSS
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://domain.tld/preload.js');
xhr.send('');
xhr = new XMLHttpRequest();
xhr.open('GET', 'http://domain.tld/preload.css');
xhr.send('');
// preload image
new Image().src = "http://domain.tld/preload.png";
}, 1000);
};

我注意到这张图片的“ajax”预加载根本不是真正的 ajax。它与我多年来一直使用的相同,只是在新图像对象的源中设置 url,然后让浏览器将其加载到缓存中。

现在假设有一个应用程序,如果它占用了一定的时间,我实际上需要取消图像的预加载。与停止加载实际 xhr 请求的 xhr.abort() 方法不同,仅将图像设置为 src 确实没有什么好方法可以做到这一点。

有什么理由像下面那样做一些事情不会预加载图像并允许取消预加载请求?

function preload(url, timeout){
this.canceltimeout = function(){
clearTimeout(this.timeout);
this.loaded = true;
return false;
}

this.abort = function(){
this.xhr.abort();
this.aborted = true;
}

//creates a closure to bind the functions to the right execution scope
this.$_bind = function(method){
var obj = this;
return function (e){ obj[method](e);};
}

//set a default of 10 second timeout
if(timeout == null){
timeout = 10000;
}

this.aborted = false;
this.loaded = false;
this.xhr = new XMLHttpRequest();
this.xhr.onreadystatechange = this.$_bind('canceltimeout');
this.xhr.open('GET', url);
this.xhr.send('');
this.timeout = setTimeout(this.$_bind('abort'), timeout);
}

var llama = new preload('/image.gif');
show_image();

function show_image(){
if(llama.loaded){
var l = new Image();
l.src = '/image.gif';
application.appendChild(l);
}else if(llama.aborted){
var l = document.createElement('p');
l.innerHTML = 'image.gif got cancelled';
application.appendChild(l);
}else{
setTimeout(show_image, 10);
}
return false;
}

最佳答案

主要缺点是,除非您已将网络服务器配置为提供 future 的新鲜度信息(Expires,或 Cache-control: max-age http header future ),网络浏览器可能会在您设置 image.src 时向服务器发出第二个 http 请求,或者只是简单地实际使用文档中的图像。如果您的 Web 服务器已发送新鲜度验证 header (last-modifiede-tag),则不会重新下载图像,但请求会向服务器询问新鲜度仍然会进行验证,这很浪费并且会增加流程的延迟。

我不知道为什么,但是当您持有对 Image() 对象的引用时,浏览器真的很喜欢缓存图像。

如果您在 Web 浏览器调试工具中查看网络面板,您会发现大多数浏览器会发出前 2 个请求,但不会发出第 3 个请求。注释掉 ajax 回调中的代码,您将看到为 #3 发出的请求

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js"></script>
<script>
var f = "0.png?" + (new Date); // 0.png should not have future freshness info headers

$.get(f, function() {
var i = new Image();
i.src = f;
});
setTimeout(function(){
//#3
var i = new Image();
i.src = f;
}, 5000);
</script>

关于javascript - 使用ajax预加载图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10843997/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com