我需要缓存一些<script src>
我通过 AJAX 收到的。目前每个调用都尝试加载src
默认情况下通过 AJAX。但问题是这个脚本在 session 中永远不会改变,我只需要在文档上重新评估这个。
为了更清楚起见,请看以下 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>
有什么解决办法吗?
最佳答案
如果为我的情况考虑一个好的解决方案...我只是用data-src
替换了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();
});
欢迎提供替代解决方案。
关于javascript - ajax内容的内联缓存<script>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16366676/