gpt4 book ai didi

javascript - 如何防止创建重复的脚本元素?

转载 作者:行者123 更新时间:2023-12-03 12:09:48 25 4
gpt4 key购买 nike

我正在使用谷歌地图,并且我正在使用它们的异步加载。

我正在使用的功能是这样的:

ready = function() {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp&' + 'libraries=places&'+'callback=initialize';
document.body.appendChild(script);
};

我正在我的 map 页面中使用它:

$.getScript('/assets/jsFile.js' ,function(){

$(document).ready(ready);
$(document).on('page:load', ready);

});

因此,当我第一次访问该页面时,一切都很顺利,但第二次访问后,脚本元素被重新创建,并且我面临以下错误:

You have included the Google Maps API multiple times on this page. This may cause unexpected errors.

如何防止分配给 ready 的函数创建重复项?

最佳答案

要使代码只运行一次,您可以使用变量来检查它是否已经运行:

var readyExecuted = false;

function ready() {
if (!readyExecuted) {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp&' + 'libraries=places&'+'callback=initialize';
document.body.appendChild(script);
readyExecuted = true;
}
};

关于javascript - 如何防止创建重复的脚本元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25005236/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com