仅在需要时加载脚本并执行

Load Script and Execute only if needed

本文关键字:脚本 执行 加载      更新时间:2023-09-26

我需要找到是否有任何div class="map"在一个页面代码笔的例子。

如果有,并且只有在这种情况下,加载Google Maps API。

然后使用它将映射加载到div中,并使用数据属性作为后期值和长值。

所以我有以下内容:

<div class="map" data-long="51.5072" data-lat="0.1275">
  Replace by map 1
</div>
<div class="map" data-long="74.0059" data-lat="40.7127">
  Replace by map 2
</div>

我正在考虑使用这样的东西(这应该只在mapdiv存在时加载):

$.getScript('https://www.google.com/jsapi', function()
{
  google.load('maps', '3', { other_params: 'sensor=false', callback: function()
  {

  }});
});

我想应用到每个地图的代码类似于谷歌地图代码:

  function initialize() {
    var map_canvas = document.getElementById('map_canvas');
    var map_options = {
      center: new google.maps.LatLng(44.5403, -78.5463),
      zoom: 8,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    var map = new google.maps.Map(map_canvas, map_options)
  }
  google.maps.event.addDomListener(window, 'load', initialize);
</script>

谢谢你,米格尔

查看异步加载Google Maps API的解决方案:https://stackoverflow.com/a/12602845/1491212

var gMapsLoaded = false;
window.gMapsCallback = function(){
    gMapsLoaded = true;
    $(window).trigger('gMapsLoaded');
}
window.loadGoogleMaps = function(){
    if(gMapsLoaded) return window.gMapsCallback();
    var script_tag = document.createElement('script');
    script_tag.setAttribute("type","text/javascript");
    script_tag.setAttribute("src","http://maps.google.com/maps/api/js?sensor=false&callback=gMapsCallback");
    (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
}

然后像这样做:

$(document).ready(function(){
    function initialize(){
        var map_canvas = document.getElementById('map_canvas');
        var map_options = {
            center: new google.maps.LatLng(44.5403, -78.5463),
            zoom: 8,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        }
        var map = new google.maps.Map(map_canvas, map_options)
    }
    $(window).bind('gMapsLoaded', initialize);
    if($('.map').length){
        window.loadGoogleMaps();
    }
});