Jquery getScript缓存 [英] Jquery getScript caching

查看:186
本文介绍了Jquery getScript缓存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

默认情况下,$ .getScript()禁用缓存,您可以使用$ .ajaxSetup并将缓存设置为true。当测试脚本是否实际上是用Firebug缓存时,脚本大部分时间都会返回200(这意味着脚本是一个新的副本),一个可能20或30次,它将返回304(意味着它使用了缓存)版)。为什么绝大部分时间都会获得新副本?

By Default $.getScript() disables caching and you can use $.ajaxSetup and set caching to true. When testing if the script is actually cached with Firebug most of the time the script is coming back at 200 (Which means the script is a fresh copy) and one in maybe 20 or 30 times it will come back 304 (meaning it used a cached version). Why is it getting a new copy the vast majority of the time?

$.ajaxSetup({
    cache: true
 });

 $.getScript( scriptFile );

getScript检索的文件尚未编辑,请求的页面更改分开。

The files that getScript retrieves have not been edited and the requests are a page change apart.

推荐答案

截至发布此问题的日期有错误,Firefox和Chrome都会声明脚本未从Cache加载确实如此。截至本答复之日,此问题仍然存在。最简单的测试方法是使用console.log并发送版本号。

There is an error as of the date this question was posted where both Firefox and Chrome would state that a script is not being loaded from Cache when it indeed is. As of the date of this answer this issue still exists. The easiest way to test is to use console.log and send out a version number.

要缓存动态加载的脚本,只需使用以下代码即可完成。

To cache a dynamically loaded script it it simply done by using the following code.

function onDemandScript ( url, callback ) {
    callback = (typeof callback != 'undefined') ? callback : {};

    $.ajax({
         type: "GET",
         url: url,
         success: callback,
         dataType: "script",
         cache: true
     });    
}

对于开发,你应该注释掉cache:true。

For development you should comment out cache: true.

这篇关于Jquery getScript缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆