您好,我在包含 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/