$.getscript_jQuery .getScript()重构以防止缓存

$.getscript

jQuery .getScript()函数的一个功能是,它为每个ajax脚本调用都包含唯一的ID(时间戳等) 。 当我运行setTimeout来获取脚本但它正在重新加载相同的脚本时,这为我带来了一个问题……不好。 因此,我决定稍微重构jQuery的.getScrip()来防止缓存,因此它只加载一次脚本

新的getScript函数

//getScript refactor to prevent caching
(function () {
    $.getScript = function(url, callback, cache)
    {
        $.ajax({
                type: "GET",
                url: url,
                success: callback,
                dataType: "script",
                cache: cache
        });
    };
})();

为了证明它是可行的 ,我在HTTP请求加载时间中进行了测试,并观察了圆圈,您可以看到脚本现在在7毫秒左右的时间内加载了缓存的版本。
getScript caching

让我们仔细看一下原始的.getScript()函数以及如何使用extra参数调用新函数

//normal no cached version
$.getScript('js/script.js', function()
{
    //do something after script loaded
});

如何调用新的.getScript()函数

如果要缓存它,只需在末尾添加true即可。

//cache = true
$.getScript('js/script.js', function()
{
    //do something after script loaded
}, true);

要么

// turn on cache
$.ajaxSetup({ cache: true });
$.getScript(url, callback);
// turn cache back off
$.ajaxSetup({ cache: false });

翻译自: https://www.sitepoint.com/jquery-getscript-refactor-prevent-caching/

$.getscript

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值