检查是否加载了外部 JS 库
Checking if external JS library is loaded or not
我当前的设置是让用户单击 link 以动态加载内容,其中还包括加载脚本。我希望能够测试是否加载了外部脚本(特别是 Google Maps JS API),如果没有加载则继续执行。
这是我的代码:
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
编辑:传感器参数不再使用,因此已从下面的代码中删除。
如果我没理解错的话,我想你可以放弃 len 的东西,只检查是否加载了 google...是这样吗?如果是,试试这个。
if (typeof google === 'object' && typeof google.maps === 'object') {
initMap();
} else {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://maps.google.com/maps/api/js?callback=initMap";
document.body.appendChild(script);
}
这会让您充满希望。祝你好运!
我当前的设置是让用户单击 link 以动态加载内容,其中还包括加载脚本。我希望能够测试是否加载了外部脚本(特别是 Google Maps JS API),如果没有加载则继续执行。
这是我的代码:
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
编辑:传感器参数不再使用,因此已从下面的代码中删除。
如果我没理解错的话,我想你可以放弃 len 的东西,只检查是否加载了 google...是这样吗?如果是,试试这个。
if (typeof google === 'object' && typeof google.maps === 'object') {
initMap();
} else {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://maps.google.com/maps/api/js?callback=initMap";
document.body.appendChild(script);
}
这会让您充满希望。祝你好运!