使用jQuery动态地向页面添加脚本从不使用缓存文件

我正在使用jQuery动态地向我的页面添加脚本并且它可以工作,但jQuery将“_ = TIMESTAMP”附加到URL,导致浏览器从不使用缓存。 使用以下代码:

       $("head").append('');    

我可以在firebug中看到所请求的URL是:

 https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.15/jquery-ui.min.js?_=1313291978667 

有谁知道如何告诉jQuery不要这样做?

谢谢

要回答原始问题,您会看到附加时间戳,因为默认情况下 jQuery会为scriptjsonp调用设置cache: false ,这会将时间戳附加到URL。

要避免使用时间戳,您可以执行以下操作:

 $.ajaxPrefilter(function( options, originalOptions, jqXHR ) { if ( options.dataType == 'script' || originalOptions.dataType == 'script' ) { options.cache = true; } }); 

这为所有$.ajax调用设置了一个全局预filter,包括jQuery在请求script所做的调用。

我们检查dataType以确保我们不会无意中针对其他ajax调用并将cache显式设置为true 。 这样可以避免时间戳附加问题。

您现在可以使用原始代码,它将从缓存中获取它。

您可以使用$.ajax来获取脚本,而不是附加脚本标记

 $.ajax({ url: "http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js", dataType: "script", cache: true,//This will decide whether to cache it or no so that it will not add the timestamp along with the request success: function(){}//In the success handler you can write your code which uses resources from this js file ensuring the script has loaded successfully before using it }); 

这是适合我的东西

 // Backup the jquery ajax cache setting var jQueryAjaxSettingsCache = jQuery.ajaxSettings.cache; // Disable the ?_=TIMESTAMP addition jQuery.ajaxSettings.cache = true; // Do the cached script inserting ... $("head").append('