将用Ajax加载的插件保存到缓存中



所以我用这个代码来更改我网站的内容,并为每个"页面"加载特定的插件:

$.ajax({
url: urlPath, 
type: 'GET',
success: loadContent //content and plugins are loaded through this
});

现在我注意到它没有缓存从loadContent加载的插件,每次一次又一次地下载它们时,使用ajax请求的页面比简单http请求慢0.5秒到1.5秒(显然是在插件已经从第一次加载缓存之后)。使用cache: true/false没有任何区别。

我读过这是不可能做到的,因为javascript不能写入磁盘,但也许我还是错过了一些东西,有一种方法可以缓存插件,避免每次加载时损失额外的时间?

您可以使用localStorage作为缓存的替代方案。每个网站都有权在用户磁盘上存储最多5 MB的数据。

所以用这个来保存数据:

//browser support localStorage
if((typeof(Storage) !== "undefined"){
localStorage.setItem("mydataname", data);
}

检索或下载一个新的:

//browser support localStorage
if((typeof(Storage) !== "undefined"){
var data = localStorage.getItem("mydataname");
if(data){ //data does exist in localStorage
// Use data, no need to download a new version.
}
else{ // data doesn't exist, not saved yet or have been removed
// download new version of data and save it using the above code.
}
}
else{
// browser doesn't support localStorage redownload data.
}

有关localStorage的更多信息,请点击此处。

最新更新