在Angular SPA中异步加载脚本

Asynchronously load script in Angular SPA

本文关键字:加载 脚本 异步 Angular SPA      更新时间:2023-09-26

我有一个Angular应用程序,其中包含指令。一个指令在调用时会构建一个mapbox映射。为了工作,我目前在应用程序最初加载时加载mapbox CSS和JS。这并不理想,因为它降低了初始页面加载的速度,但用户甚至可能无法访问需要此脚本的视图。

因此,我的问题是,当第一次调用指令时,是否有异步加载脚本(可能还有CSS)的方法。第一次之后,如果在另一个视图中再次使用该指令,则不应再次加载脚本。angular-loader.js也可以这样做吗?

到目前为止,我的示例设置如下:

查看HTML

<ng-map></ng-map>

指令

app.directive('ngMap', ['MapService', function(MapService){
  return {
    restrict: 'E',
    templateUrl: '/partials/map.html',
    link: function($scope, element, attrs){
      MapService.build();      
    }
  }
}]);

服务

app.service('MapService', [function(){
  this.build = function(){    
    //map bounds
    var southWest = L.latLng(54.04407014753034, -0.745697021484375),
        northEast = L.latLng(53.45698455620496, -2.355194091796875),
        bounds = L.latLngBounds(southWest, northEast);
    //build map object
    L.mapbox.accessToken = conf.mapbox.token;
    map.obj = L.mapbox.map('map', conf.mapbox.id, {
      maxBounds: bounds,
      zoomControl: false,
      minZoom: 11,
      attributionControl: false
    }).setView([53.80451586014786, -1.5477633476257324], 15, {
      pan: { animate: true },
      zoom: { animate: true } 
    });
  };
}]);

map.html

<div id="map"></div>

您可以使用requirejs和angular,如下所述。