我目前的设置有一个链接,在用户点击动态加载的内容,其中还包括在脚本加载检查。我希望能够测试是否加载了外部脚本(特别是Google Maps JS API),如果不是,则继续前进。如果外部JS库加载与否
这里是我的代码:
if(_href == "contact.html") {
// this will run everytime we navigate/click to go to "contact.html"
console.log("contact.html loaded");
// load the contact.js script, and once loaded,
// run the initMap function (located inside contact.js) to load the map
$.getScript("contact.js", function() {
// store the length of the script, if present, in a varialbe called "len"
var len = $('script[src="https://maps.googleapis.com/maps/api/js"]').length;
console.log(len);
// if there are no scripts that match len, then load it
if (len === 0) {
// gets the script and then calls the initMap function to load the map
$.getScript("https://maps.googleapis.com/maps/api/js", initMap);
console.log("Google Maps API loaded")
} else {
// otherwise the script is already loaded (len > 0) so just run the initMap function
initMap();
}
});
但是,这是行不通的。每当用户点击去接触网页时,“LEN”始终为0,该脚本是否被实际加载已经(“LEN”时,它的加载应大于0)。它会导致日志中出现此错误: log error
我真的很困惑,回调'$ .getScript'脚本总是加载,但你装'contact.js'和似乎期望谷歌地图被加载,即使这两个脚本唐彼此似乎没有任何关系? – adeneo
你可以找到http://stackoverflow.com/questions/9521298/verify-external-script-is-loaded – user86745458
答案@adeneo对不起,如果我让你感到困惑,但我只学习web开发的一个月现在:p我希望这可以回答你的问题:'contact.js'包含一个函数,它需要首先加载谷歌地图 - 这个js文件基本上创建地图,设置其参数等 - 所以这是必须的谷歌地图第一加载,否则我会得到一个错误。在我调用contact.js中的函数之前,我需要加载contact.js和Google Maps API。我只希望谷歌地图加载一次,否则我得到一个错误(但是,我没有得到任何这样的错误而载入'contact.js' – Attila