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

Les*_*nks 13 javascript jquery

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

<!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>
Run Code Online (Sandbox Code Playgroud)

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

https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.15/jquery-ui.min.js?_=1313291978667
Run Code Online (Sandbox Code Playgroud)

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

谢谢

Mrc*_*ief 25

要回答你原来的问题,你看追加因为jQuery时间戳默认设置cache: falsescriptjsonp其附加的时间戳的URL电话.

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

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

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

我们检查dataType以确保我们不会无意中针对其他ajax调用并明确设置cachetrue.这样可以避免时间戳附加问题.

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


Sha*_*oli 7

您可以使用$.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
});
Run Code Online (Sandbox Code Playgroud)