动态加载脚本文件

动态加载脚本文件

本文介绍了AngularJS-使用 LazyLoad-Webpack 动态加载脚本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在在我的 index.html 页面中,我有两个 CDN 文件的链接,一个是 JS 文件,另一个是 CSS 文件.

Right now in my index.html page I have links to two CDN files one being a JS and the other a CSS file.

即在我身体的底部

https://somedomain.com/files/js/js.min.js

在头部

https://somedomain.com/files/css/css.min.css

但现在我的主页上不需要它们,而只是在一个特定的路线上.所以我正在研究如何在路由被命中时延迟加载这些 CDN 资源,即 /profile 然后才加载?

But right now they aren't needed on my homepage but just in one particular route. So I was looking into how I can lazy load these CDN resources when that routes gets hit i.e. /profile and only then ?

这些不是通过 bower 或 npm 安装的,而是通过 CDN url 加载的,例如 jquery.如何在 Angular 1 和 Webpack 中基于路由延迟加载?

These aren't installed via bower or npm but just loaded via CDN url for example jquery. How in Angular 1 and Webpack can I lazy load that based on a route ?

推荐答案

给你.. 使用 oclazyload 使其成为可能.看看下面的代码.下面链接的一个plunker

Here you go.. It is made possible using oclazyload. Have a look at below code. A plunker linked below

我有一个名为 myApp 的模块,如下所示

I have a module Called myApp as below

angular.module('myApp', ['ui.router','oc.lazyLoad'])
    .config(function ($stateProvider, $locationProvider, $ocLazyLoadProvider) {
            $stateProvider
                .state("home", {
                    url: "/home",
                    templateUrl: "Home.html",
                    controller: 'homeCtrl',
                    resolve: {
                        loadMyCtrl: ['$ocLazyLoad', function ($ocLazyLoad) {
                            return $ocLazyLoad.load('homeCtrl.js');
                        }]
                    }
                })
            .state("profile", {
                url:"/profile",
                templateUrl: "profile.html",
                 resolve: {
                      loadMyCtrl: ['$ocLazyLoad', function ($ocLazyLoad) {
                      return $ocLazyLoad.load('someModule.js');
                        }]
                    }
            })

    });

我有另一个名为 someApp 的模块,如下所示

I have another module called someApp as below

(function () {
var mynewapp=angular.module('someApp',['myApp']);

mynewapp.config(function(){

  //your code to route from here!

});
      mynewapp.controller("profileCtrl", function ($scope) {

            console.log("reached profile controller");
        });

})();

我有一个 Live Plunker 用于您的演示 这里

I have a Live Plunker for your demo here

这篇关于AngularJS-使用 LazyLoad-Webpack 动态加载脚本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 19:08