我在一个页面上有两个jQuery脚本。两者都独立地执行不同的操作,但使用从$.getJSON()
的同一URL加载的相同JSON数据。数据相当大,所以我想避免两次下载。
事情是,不能保证当时页面上会包含机器人脚本。通常两者都需要,但有时只需要其中一个。
我应该如何编码$.getJSON()
逻辑以确保数据不会被下载两次,但同时两个脚本都能够独立下载数据,以防只有一个脚本是包括?
答案 0 :(得分:0)
你应该在$ .getJSON调用之前存储数据$ .getJSON gets并检查该变量。
if (typeof jsondata === 'undefined') {
$.getJSON('url', function(data){
var jsondata=data;
}
}
//use the jsondata variable
答案 1 :(得分:0)
您可以利用getJSON
方法返回实现Promise
接口的对象这一事实。伪代码示例......
主要剧本:
var MyApp = MyApp || {};
(function () {
// create a local variable to hold the promise
var promise = null;
this.getData = function () {
if ( promise === null ) {
// make the call and store the promise only
// if it hasn't already been created yet
promise = $.getJSON(...).promise();
}
return promise;
};
}).apply( MyApp );
然后在您的两个脚本(以及可能需要相同数据的任何其他脚本)中,您可以执行以下操作:
$.when( MyApp.getData() ).done( function ( data ) {
// do something with data
});
一些好处:
getJSON
getData
(或多久)时,这并不重要。即使承诺已经解决,它们也始终能够在done
处理程序中访问从服务器返回的数据。