Right now in my index.html
page I have links to two CDN files one being a JS and the other a CSS file.
i.e. in the the bottom of my body
https://somedomain.com/files/js/js.min.js
and in the head
https://somedomain.com/files/css/css.min.css
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 ?
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 ?
Here you go.. It is made possible using oclazyload. Have a look at below code. A plunker linked below
I have a module Called myApp as below
I have another module called someApp as below
I have a Live Plunker for your demo here
I have this JStaticLoader repo, to ease me loading static files whenever I need them. Though, it's not angularized, but you can still use it in your app as a
directive
, direct call it from yourcontroller
or even in the$rootScope
to load your desiredjs
.JStaticLoader
uses pure js and require no dependencies. It usesXMLHttpRequest
to load the static files.As an example use in your
app.js
(on$routeChangeStart
or$stateChangeStart
)On the sample above, I get a
js
file by using xhr, and append it as ascript
in mydocument
once it's finished. The script will then be loaded from your browser's cache.Strictly talking about the Webpack -
I will demonstrate only some of the modules which you can try,as there are many such defined on the web.
Therefore a better way to lazy load the cdn from the another domain would be using the javascript loader - script.js
It can be loaded in the following way -
This is possible because the script-loader just evaluates the javascript in the global context.
References here
Concerning about the issue of lazy loading the cdn into the angular app
The following library Lab JS is made specifically for this purpose. It becomes very simple to load and bloack the javascript using this library.
Here is an example to demonstrate
OR
You can use the require.js
Here is an example to load the jquery
You should also consider the following paragraph from this article.