【问题标题】:Load Google Maps javascript file when need需要时加载 Google Maps javascript 文件
【发布时间】:2017-09-20 09:43:24
【问题描述】:

我有一个带有按钮的页面,可以在模式中打开地图。由于只有少数用户会使用此功能,我想知道是否可以仅在需要时加载 Google 地图库(在这种情况下,我更喜欢用户等待而不是每次加载页面时都等待)。

这是我的模态:

<div class="modal" id="showBuildingsMaps" data-backdrop="static"
    data-keyboard="false">
    <div class="modal-dialog modal-lg">
       <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
                <h4 class="modal-title">Select building</h4>
            </div>
            <div class="modal-body">
                <div class="box-body" style="height: 80vh;">
                    <ng-map zoom="3" center="[{{selectedBuilding.latitude}}, {{selectedBuilding.longitude}}]" default-style="false"> 
                       <marker ng-repeat="m in markers" position="{{m.latitude}},{{m.longitude}}" title="{{m.name}}"
                                        on-click="buildingFromMaps(m)"></marker> </ng-map>
                </div>
            </div>
        </div>
        <!-- /.modal-content -->
    </div>
    <!-- /.modal-dialog -->
</div>

还有几个谷歌地图库:

<!-- Maps -->
<script
    src="https://maps.googleapis.com/maps/api/js?key={myKey}"
    type="text/javascript">
    </script>
<!-- is useful to avoid google not found exception before this script was loaded bedore google maps -->
<script defer
    th:src="@{/static/assets/plugins/angular-maps/ng-map.min.js}"
    type="text/javascript"></script>
<script
    src="https://rawgit.com/allenhwkim/angularjs-google-maps/master/testapp/scripts/markerclusterer.js"
    type="text/javascript"></script>
<script>
    MarkerClusterer.prototype.MARKER_CLUSTER_IMAGE_PATH_ 
      = 'https://raw.githubusercontent.com/googlemaps/js-marker-clusterer/gh-pages/images/m';  //changed image path 
  </script>

【问题讨论】:

  • 您是否有任何延迟加载设置。在你的角度应用程序中?喜欢 oclazyload?
  • 不,我没有任何延迟加载
  • 那么我能想到的最快的解决方案是将脚本标记的负载包装在指令中并将其放入您的 dialog.html 中。因此,只有在编译对话框时才会加载脚本。检查这个所以回答。 stackoverflow.com/questions/19917774/… 在此处查看解决方案。

标签: javascript jquery html twitter-bootstrap google-maps


【解决方案1】:

将 onclick 添加到您的按钮

<button type="button" onclick="loadGoogleMaps()" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>

然后是这样的

<script>
function loadGoogleMaps() {
var mapScript = document.createElement('script');
mapScript.src = put your source here;

document.head.appendChild(script);
}
</script>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-28
    • 2018-09-02
    • 2011-07-04
    • 2010-10-26
    • 2020-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多