如何确保JavaScript仅加载一次 [英] How to ensure that the javascript is loaded only once

查看:173
本文介绍了如何确保JavaScript仅加载一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用jquery getScript()调用JS.

I am calling a JS using jquery getScript().

有时候我可以看到文件已经被加载(缓存的资源). 因此,刷新时不会删除缓存的页面,并且还会再次加载相同的文件.

Sometimes i could see that the files are already loaded (cached resource). So,On refreshing the cached page is not removed and also the same file is loaded again.

由于同一个文件包含多个内容,因此出现错误.

Because of the multiple includes of the same file i am getting errors.

如何避免这种情况?

$.getScript("http://localhost:8888//../../demo.js", function() { console.log('Script is loaded.'); });

$.getScript("http://localhost:8888//../../demo.js", function() { console.log('Script is loaded.'); });

推荐答案

默认情况下,$.getScript将缓存设置设置为false.尝试将其设置为true来查看是否可以解决您的问题:

By default, $.getScript sets the cache setting to false. Try setting it to true to see if this solves your problem:

$.ajaxSetup({
  cache: true
});

在通话前添加以下内容:

Add the above before your call like:

$.ajaxSetup({
      cache: true
    });

$.getScript("http://localhost:8888//../../demo.js", function() { console.log('Script is loaded.'); });

直接从jquery 文档:

directly from jquery docs:

缓存响应

默认情况下,$.getScript()将缓存设置设置为false.这 将带有时间戳的查询参数附加到请求URL,以确保 浏览器在每次请求时都会下载脚本.你 可以通过使用以下命令全局设置缓存属性来覆盖此功能 $ .ajaxSetup():

By default, $.getScript() sets the cache setting to false. This appends a timestamped query parameter to the request URL to ensure that the browser downloads the script each time it is requested. You can override this feature by setting the cache property globally using $.ajaxSetup():

$.ajaxSetup({cache:true});或者,您可以定义 一种使用更灵活的$ .ajax()方法的新方法.

$.ajaxSetup({ cache: true }); Alternatively, you could define a new method that uses the more flexible $.ajax() method.

示例:示例:定义一个$ .cachedScript()方法,该方法允许 提取缓存的脚本:

Examples: Example: Define a $.cachedScript() method that allows fetching a cached script:

jQuery.cachedScript = 函数(网址,选项){ //允许用户设置除dataType,cache和url以外的任何选项options = $ .extend(options || {},{ dataType:脚本", 快取:true, url:url}); //使用$ .ajax(),因为它比$ .getScript更灵活//返回jqXHR对象,以便我们可以链接回调return jQuery.ajax(options); };//用法$ .cachedScript("ajax/test.js" ).done(function(脚本,textStatus){console.log(textStatus); });

jQuery.cachedScript = function( url, options ) { // Allow user to set any option except for dataType, cache, and url options = $.extend( options || {}, { dataType: "script", cache: true, url: url }); // Use $.ajax() since it is more flexible than $.getScript // Return the jqXHR object so we can chain callbacks return jQuery.ajax( options ); }; // Usage $.cachedScript( "ajax/test.js" ).done(function( script, textStatus ) { console.log( textStatus ); });

这篇关于如何确保JavaScript仅加载一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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