How to handle multiple JS libraries with different loading times in Angular?

前端 未结 3 1282
渐次进展
渐次进展 2021-01-23 15:13

I am just learning Angular and I have some questions regarding the architecture of my app.

The project I will be working on will be using allot of external libraries: jQ

3条回答
  •  旧巷少年郎
    2021-01-23 15:30

    I'm not sure this is the "correct" way to do this, but here is perhaps a simpler way to handle external libraries (in this case d3.js) within Angular 1.x code.

    This is the same basic idea as @aarosil's answer (use a factory), but using fewer dependencies on other services - for what that's worth.

    var app = angular.module('SomeApp', []);
    app.factory('LibraryFactory', function () {
        var factory = {};
    
        factory.getD3 = function(callback) {
            if(!window.d3) {
                var script = document.createElement("script");
                script.src = "https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.9/d3.min.js";
                document.head.appendChild(script);
                script.onload = function() {
                    callback(window.d3);
                };
            } else {
                callback(window.d3);
            }
        };
    
        //factory.getSomeOtherLibrary = ...ditto
    
        return factory;
    });
    

    And to use the factory (eg, in a controller):

    app.controller('SomeTrialWithD3Ctrl', function ($scope, LibraryFactory) {
    
        LibraryFactory.getD3(function main(d3) {
            // place code using d3 library here
        });
    });
    

    And of course, the callbacks can be chained if you need multiple libraries at once.

提交回复
热议问题