发现这种使用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);
};
Run Code Online (Sandbox Code Playgroud)
我注意到这个图像的'ajax'预加载实际上并不是真正的ajax.它与我多年来一直使用的相同,只是在新图像对象的源中设置url并让浏览器将其加载到缓存中.
现在假设有一个应用程序,如果它占用了一定的时间,我需要实际取消图像的预加载.只需将图像设置为src就没有好办法,不像xhr.abort()方法停止加载实际的xhr请求.
是否有任何理由做像下面这样的事情也不会预先加载图像并允许取消预加载请求?
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 …Run Code Online (Sandbox Code Playgroud)