これは手斧のようなものですが、動的なコールバックを取得できます。file:
基本的には、転送がかなり高速になるという事実に依存しています。リクエストのキューを設定し、一度に 1 つずつ送信します。これが、正しい応答とコールバックを (保証された順序で) リンクできることを確認する唯一の方法でした。うまくいけば、誰かがより良い方法を考え出すことができますが、応答を動的に生成することができないため、これが私ができる最善の方法です.
var JSONP = {
queue: [],
load: function(file, callback, scope) {
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = "text/javascript";
script.src = file;
head.appendChild(script);
},
request: function(file, callback, scope) {
this.queue.push(arguments);
if (this.queue.length == 1) {
this.next();
}
},
response: function(json) {
var requestArgs = this.queue.shift();
var file = requestArgs[0];
var callback = requestArgs[1];
var scope = requestArgs[2] || this;
callback.call(scope, json, file);
this.next();
},
next: function() {
if (this.queue.length) {
var nextArgs = this.queue[0];
this.load.apply(this, nextArgs);
}
}
};
これは私がテストするためにしたことです
window.onload = function() {
JSONP.request('data.js', function(json, file) { alert("1 " + json.message); });
JSONP.request('data.js', function(json, file) { alert("2 " + json.message); });
}
Data.js
JSONP.response({
message: 'hello'
});