嗨,我在包含JavaScript特别是Google Maps 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 maps api的窗口小部件时,即使我最初不在此页面中包含maps 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;
}
}
该功能并非完全必要,但可以使所有内容变得更加整洁。