您已在此页面上多次包含Google Maps JavaScript API.这可能会导致意外错误.使用$ .getScript()调用时 [英] You have included the Google Maps JavaScript API multiple times on this page. This may cause unexpected errors. when called using $.getScript()

查看:291
本文介绍了您已在此页面上多次包含Google Maps JavaScript API.这可能会导致意外错误.使用$ .getScript()调用时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

序言: 我已经将Google地图和地理定位实现为独立的小部件,现在用户可以在自己拥有的页面中根据需要添加任意数量的小部件. 我正在使用$ .getScript(URl,callback)来加载该URL的脚本.

Prelog: I have implemented Google maps and Geolocation as a independent widgets, Now the user have the ability to add the widget as much as he wants in a page he is owns. I am using $.getScript(URl, callback) to load the script for that URL to work.

问题: 当用户在同一页面中多次添加两个窗口小部件或同一窗口小部件时,检查windows.google失败,并且两次执行$ .getScript(url,callback).由于这个原因,我从Google脚本中得到了一个错误

Problem : When the user add both the widgets or the same widget multiple times in a same page , the check windows.google fails and the $.getScript(url, callback) gets executed twice. Due to which I get an error from the Google Script

您已多次包含Google Maps JavaScript API 这一页.这可能会导致意外错误.当使用 $ .getScript()

You have included the Google Maps JavaScript API multiple times on this page. This may cause unexpected errors. when called using $.getScript()

if(window.google !== undefined && window.google !== null) {
    onScriptLoad(null, null, 200);
} else {
    $.getScript(googleUrl, onScriptLoad);
}

以上行在两个小部件中都存在,并且两个小部件彼此独立.它总是进入两个函数的else块. 期待这里有一些解决方法,例如使用javascript或jquery同步加载脚本

The above line exists in both the widget and both the widgets are independent of each other. It always goes into the else block of both the functions. Looking forward for some work around here, like to load the script synchronously using javascript or jquery

推荐答案

当您的代码在第一个 widget 中运行时,它会启动google API的加载,但是不会创建window.google直到脚本完成加载.这是异步

when your code runs in the first widget, it initiates the loading of the google API, however window.google isn't created until the script completes loading. This is asynchronous

现在,第二个 widget 测试window.google是否存在,但这在Google API加载之前仍在发生,因此,它也认为需要加载google API

Now, the second widget tests if window.google exists, but this is still happening before the google API loads, therefore, it too thinks it needs to load google API

所以,代替这个:

if(window.google !== undefined && window.google !== null) {
    onScriptLoad(null, null, 200);
} else {
    $.getScript(googleUrl, onScriptLoad);
}

尝试

window.loadingGoogleApi = window.loadingGoogleApi || $.getScript(googleUrl);
window.loadingGoogleApi.then(onScriptLoad);

loadingGoogleApi可以是您选择的任何名称(只是不要使用会被其他代码破坏的名称)

the loadingGoogleApi can be any name you choose (just don't use something that will be clobbered by other code)

这篇关于您已在此页面上多次包含Google Maps JavaScript API.这可能会导致意外错误.使用$ .getScript()调用时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆