AngularJS - load google map script async in directive for multiple maps

前端 未结 1 1574
离开以前
离开以前 2020-12-08 15:15

I am currently trying to load multiple google maps on a single page. I don\'t want to include google map API script into the HTML code as I don\'t want the script to be load

1条回答
  •  南笙
    南笙 (楼主)
    2020-12-08 16:09

    you have a problem here with promises and initialisation, i've made it cleaner for you

    Apparently the jsfiddle has been removed so here is working plunker: http://plnkr.co/edit/1NpquJ?p=preview

    js

    here is a service for lazy load gmaps

    app.service('lazyLoadApi', function lazyLoadApi($window, $q) {
      function loadScript() {
        console.log('loadScript')
        // use global document since Angular's $document is weak
        var s = document.createElement('script')
        s.src = '//maps.googleapis.com/maps/api/js?sensor=false&language=en&callback=initMap'
        document.body.appendChild(s)
      }
      var deferred = $q.defer()
    
      $window.initMap = function () {
        deferred.resolve()
      }
    
      if ($window.attachEvent) {
        $window.attachEvent('onload', loadScript)
      } else {
        $window.addEventListener('load', loadScript, false)
      }
    
      return deferred.promise
    });
    

    then the directive does what it should do, work only with map, don't load js files on any other logic

    0 讨论(0)
提交回复
热议问题