我有下面的代码,如果URL不正确,应该抛出错误。然而,即使URL明显不正确,实际上也没有发生任何事情。
function loadApi() {
var script = document.createElement('script');
script.src = 'https://maps.googleapiss.com/maps/api/js?key={key}&libraries=geometry';
script.onerror = function() {
exit('MarvMap: Unable to load Google Map API, please check the URL.');
};
script.onload = function () {
document.head.appendChild(this);
};
}
function exit(message = 'Exiting MarvMap') {
throw new Error(message);
}
答案 0 :(得分:2)
除非您将元素附加到DOM,否则脚本不会被加载。如果你这样做,你会看到错误:
function loadApi() {
var script = document.createElement('script');
script.onerror = function() {
exit('MarvMap: Unable to load Google Map API, please check the URL.');
};
script.onload = function () {
console.log("Loaded");
};
script.src = 'https://maps.googleapiss.com/maps/api/js?key={key}&libraries=geometry';
document.head.appendChild(script);
}
(我还习惯性地在设置src
之前挂钩处理程序,因为它与图像有关。但不是脚本。)