使用jQuery动态地向页面添加脚本从不使用缓存文件 [英] Adding a script to the page dynamically with jQuery never uses the cached file
问题描述
我正在使用jQuery动态地将脚本添加到我的页面并且它可以工作,但是jQuery将_ = TIMESTAMP附加到URL,导致浏览器永远不会使用缓存。使用以下代码:
I am using jQuery to dynamically add a script to my page and it works, but jQuery appends "_=TIMESTAMP" to the URL causing the browser to never use the cache. With the following code:
<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>
<html xmlns='http://www.w3.org/1999/xhtml'>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$("head").append('<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.15/jquery-ui.min.js"></scr' + 'ipt>');
</script>
</body>
</html>
我可以在firebug中看到所请求的URL是:
I can see in firebug that the URL requested is:
https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.15/jquery-ui.min.js?_=1313291978667
有谁知道如何告诉jQuery不要这样做?
Does anyone know how to tell jQuery not to do this?
谢谢
推荐答案
要回答原始问题,您会看到附加的时间戳,因为jQuery 默认情况下设置 cache:false
for script
和 jsonp
将时间戳附加到URL的调用。
To answer your original question, you see the timestamp appended because jQuery by default sets cache: false
for script
and jsonp
calls which appends the timestamp to the URL.
为了避免时间戳,你可以这样做:
To avoid the timestamp, you can do this:
$.ajaxPrefilter(function( options, originalOptions, jqXHR ) {
if ( options.dataType == 'script' || originalOptions.dataType == 'script' ) {
options.cache = true;
}
});
这会设置全局 $。ajax 调用的.ajaxPrefilter /rel =noreferrer> prefilter ,包括jQuery在请求时所做的调用脚本
。
This sets up a global prefilter for all $.ajax
calls, including the ones made by jQuery while requesting the script
.
我们检查 dataType
以确保我们不会无意中针对其他ajax调用并明确设置缓存
到 true
。这样可以避免时间戳附加问题。
We inspect the dataType
to make sure we're not inadvertantly targetting other ajax calls and explicitly set cache
to true
. This will avoid the timestamp appending problem.
您现在可以使用原始代码,它将从缓存中提取。
You can now use your original code and it'll pick it up from cache.
这篇关于使用jQuery动态地向页面添加脚本从不使用缓存文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!