Search code examples
javascriptarcgisarcgis-js-api

Dynamically load ArcGIS online modeule


It is possible to dynamically decide which models to require()?

It takes a while to load a bunch of widgets, using the JavaScript require() function, so I want to be able to only include the ones I'm using in any given instance to the ones I'm using.

Currently, I do this:

var reqs="esri/Map", "esri/WebMap", ... "esri/widgets/Legend";
require(reqs, function(Map, WebMap, ... ,Legend,) { 
...

It's easy enough to fill the reqs array, but how can I vary the names in the function?


Solution

  • Not sure in which situation you would want to dynamically change the imports at runtime as the code where they are used is most likely static. Do you mean changing the list of imports?

    You can always change this

    require(
      ["esri/Map", "esri/WebMap", "esri/widgets/Legend"],
      function(Map, WebMap, Legend) {
    
       // Source code using Map, WebMap and Legend
    
      });
    

    to the list of dependencies you need:

    require(
      ["esri/Map", "esri/SceneView", "esri/layers/KMLLayer"],
      function(Map, WebMap, KMLLayer) {
    
       // Source code using Map, SceneView and KMLLayer
    
      });
    

    See the ArcGIS API for JavaScript samples that all have different require() statements.


    If you meant lazy-loading to reduce initial startup time, there is a nice modular example using Webpack and TypeScript:

    https://github.com/Esri/jsapi-resources/tree/master/4.x/webpack/demo

    It imports/requires all ArcGIS API for JavaScript classes after the main UI is finished loading. This is essentially done by calling import / require inside a method:

    https://github.com/Esri/jsapi-resources/blob/master/4.x/webpack/demo/src/widgets/App.tsx#L53