Jquery append()和appendTo()追加多个元素

时间:2015-02-22 15:50:10

标签: javascript jquery google-maps

我正在为谷歌地图尝试推迟加载,它应该在触发模态时加载:

$( document ).on( "shown.bs.modal", function(){
        $script = $("<script>", {'type': 'text/javascript', 'src': 'https://maps.googleapis.com/maps/api/js?signed_in=true&callback=initialize'});
        $script.appendTo($("head"));
});

但我有多个脚本行:

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?signed_in=true&amp;callback=initialize"></script>

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?signed_in=true&amp;callback=initialize"></script>

控制台:

 You have included the Google Maps API multiple times on this page. This may cause unexpected errors.main.js:59 klmain.js:60 (anonymous function)js?signed_in=true&callback=initialize&_=1424619719408:21 google.maps.Loadmain.js:60 (anonymous function)main.js:61 (anonymous function)

我怎么只追加一行? 还是有另一种方法(jquery)?

非常感谢。 Salu2

1 个答案:

答案 0 :(得分:0)

您可以检查google.maps是否已经可用,何时运行initialize,否则加载API:

$( document ).on( "shown.bs.modal", function(){
   if(window.google && window.google.maps){
     initialize();
     return;
   }
        $script = $("<script>", 
                    {'type': 'text/javascript', 
                     'src': 'https://maps.googleapis.com/maps/api/js?signed_in=true&callback=initialize'});
        $script.appendTo($("head"));
});