Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
187 views
in Technique[技术] by (71.8m points)

javascript - Adding a script to the page dynamically with jQuery never uses the cached file

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>

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

Does anyone know how to tell jQuery not to do this?

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;
  }
});

This sets up a global prefilter for all $.ajax calls, including the ones made by jQuery while requesting the script.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...