gpt4 book ai didi

javascript - PHP : Preventing multiple javascript inclusions

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

您好,我在包含 javascript(特别是 Google map API)时遇到问题。

例如,我有一个包含该库的页面:

<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=places,visualization"></script>

//some page contents

$this->widget('MyWidgetThatIncludesGoogleAPI',array(
..
));

当我调用我的小部件(其中还包括 google map api)时,即使我最初没有在此页面中包含 map api,也会出现问题。调用该小部件两次效果相同。

我收到一条错误消息,提示 Google Maps API 已加载多次,是否有编程方式来处理 js 的重复包含?

最佳答案

您可以使用全局变量来跟踪它是否已被包含。然后,您可以创建一个函数来包含该脚本(如果尚未包含该脚本)。

$includedGoogleMaps = false;
function includeGoogleMaps() {
global $includedGoogleMaps;
if (!includedGoogleMaps) {
echo '<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=places,visualization"></script>';
$includeGoogleMaps = true;
}
}

该功能并不是完全必要的,但它使一切变得更加清晰。

关于javascript - PHP : Preventing multiple javascript inclusions,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26351488/

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