私が作成したこのスクリプトローダーのようなものを使用してください:
var scriptLoader = [];
/*
* loads a script and defers a callback for when the script finishes loading.
* you can also just stack callbacks on the script load by invoking this method repeatedly.
*
* opts format: {
* url: the url of the target script resource,
* timeout: a timeout in milliseconds after which any callbacks on the script will be dropped, and the script element removed.
* callbacks: an optional array of callbacks to execute after the script completes loading.
* callback: an optional callback to execute after the script completes loading.
* before: an optional callback to execute before the script is loaded, only intended to be ran prior to requesting the script, not multiple times.
* success: an optional callback to execute when the script successfully loads, always remember to call script.complete at the end.
* error: an optional callback to execute when and if the script request fails.
* }
*/
function loadScript(opts) {
if (typeof opts === "string") {
opts = {
url: opts
};
}
var script = scriptLoader[opts.url];
if (script === void 0) {
var complete = function (s) {
s.status = "loaded";
s.executeCallbacks();
};
script = scriptLoader[opts.url] = {
url: opts.url,
status: "loading",
requested: new Date(),
timeout: opts.timeout || 10000,
callbacks: opts.callbacks || [opts.callback || $.noop],
addCallback: function (callback) {
if (!!callback) {
if (script.status !== "loaded") {
script.callbacks.push(callback);
} else {
callback();
}
}
},
executeCallbacks: function () {
$.each(script.callbacks, function () {
this();
});
script.callbacks = [];
},
before: opts.before || $.noop,
success: opts.success || complete,
complete: complete,
error: opts.error || $.noop
};
script.before();
$.ajax(script.url, {
timeout: script.timeout,
success: function () {
script.success(script);
},
error: function () {
script.error(); // .error should remove anything added by .before
scriptLoader[script.url] = void 0; // dereference, no callbacks were executed, no harm is done.
}
});
} else {
script.addCallback(opts.callback);
}
}
loadScript({
url: 'http://fiddle.jshell.net/js/lib/mootools-core-1.4.5-nocompat.js',
callback: function(){
alert('foo');
}
});
一般的に言えば、ブロックするのではなく実行を延期して、ユーザーが知覚するページの読み込み速度を上げる必要があります。