按顺序异步加载JS脚本(等待前一个脚本完成) [英] Load JS scripts asynchronously in order (waiting the previous one is complete)
本文介绍了按顺序异步加载JS脚本(等待前一个脚本完成)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用 GoogleMaps.InfoBox 在我的项目中,但在加载此脚本之前,必须加载GoogleMaps API。
I am trying to use GoogleMaps.InfoBox on my project, but before load this script, the GoogleMaps API has to be loaded.
现在我有了这段代码来加载所有内容:
Right now I have this code to load everything:
/**
* Load scripts asynchronously
*/
function loadScript() {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://maps.googleapis.com/maps/api/js?key=-MY-KEY-&sensor=true&callback=initialize";
document.body.appendChild(script);
var scriptInfoBox = document.createElement("script");
scriptInfoBox.type = "text/javascript";
scriptInfoBox.src = "http://google-maps-utility-library-v3.googlecode.com/svn/trunk/infobox/src/infobox_packed.js";
document.body.appendChild(scriptInfoBox);
}
但GoogleMaps API加载之前并不总是加载GoogleMaps.InfoBox。
But not always the GoogleMaps API is loaded before than GoogleMaps.InfoBox one.
如何加载JS排序,等待完成上一个?
推荐答案
您可以使用脚本的 load
事件:
You can use the load
event of the scripts:
function loadScript(callback) {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://maps.googleapis.com/maps/api/js?key=-MY-KEY-&sensor=true&callback=initialize";
document.body.appendChild(script);
script.onload = function() {
var scriptInfoBox = document.createElement("script");
scriptInfoBox.type = "text/javascript";
scriptInfoBox.src = "http://google-maps-utility-library-v3.googlecode.com/svn/trunk/infobox/src/infobox_packed.js";
document.body.appendChild(scriptInfoBox);
scriptInfoBox.onload = callback;
};
}
但是,您需要调整一下代码才能使其成为这样的crossbrowser-safe 。
However, you will need to adapt the code a bit to make it crossbrowser-safe like this.
这篇关于按顺序异步加载JS脚本(等待前一个脚本完成)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文