我需要缓存一些通过AJAX接收到的<script src>
。目前,每个调用都尝试通过AJAX加载src
,这是默认的。但是问题是,这个脚本在会话中永远不会改变,我只需要在文档中重新使用这个脚本。
更清楚的是,以这个AJAX内容结果为例:
<strong>Hello World!</strong>
<script src="hello-world.js"></script>
如果我三次调用这个AJAX,那么hello-world.js
也会被调用三次,但是我只需要重新执行它,而不需要再次下载它。浏览器缓存有很大帮助,但我真的不能每次都下载它。
我喜欢将一些data
设置为script
,让jQuery知道我只想重新执行它,而不是再次下载。比如:
<script src="hello-world.js" data-cache="true"></script>
有解决办法吗?
发布于 2013-05-03 20:02:06
如果为我的案子想个好办法..。我刚刚用data-src
替换了data-src
,所以jQuery不会自动获取内容,所以我有时间处理我的内容,找到data-src
并创建自己的缓存系统。对我来说很好。
您可以在这里检查我的代码:
// Cache system (outside of AJAX engine)
var script_cache = {};
// Inside of [jQuery.ajax].success method
// where "data_html" is my jQuery(data_html) AJAX response.
// Find all script with data-src
jQuery('script[data-src]', data_html).each(function() {
var self = jQuery(this),
self_src = self.data('src');
// If data was loaded before, so just execute it again
if(typeof script_cache[self_src] !== "undefined") {
jQuery.globalEval(script_cache[self_src]);
}
// Else, will load, cache and execute now
// Note that we download with dataType text
else {
jQuery.ajax(self_src, {
dataType: "text"
}).success(function(data) {
script_cache[self_src] = data;
jQuery.globalEval(data);
});
}
// Finally we remove the node, only to avoid problem
self.remove();
});
欢迎其他解决办法。
https://stackoverflow.com/questions/16366676
复制相似问题