edt edt - 28 days ago 8
AngularJS Question

Load JavaScript on demand after lightbox is displayed

There is a button on every page of my site. When the button is clicked, a lightbox appears. The content of the lightbox is a form that relies on several JavaScript files including Angular. Those JavaScript files are used only for the form and nowhere else on the site.

In order to reduce page load time, my goal is to load the JavaScript files only after the user clicks the button.

Is there a best practice way of doing this? Some options I can think of are:

  1. The content of the lightbox is an iframe and the sourced html
    document contains script tags.

  2. Use the jquery.getscript method (or similar) to load the scripts

Is there a better way?


By understanding your question, You want to lazy-load your js/css/html . You can achieve this using two plugins


Pros :

  1. Explicit dependencies between modules, listed in code.
  2. Asynchronous module loading.
  3. Lazy (on-demand) module loading.
  4. Support for one of the standard module wrappers (AMD), a lot of community modules implement it, so your modules can depend on them.

Cons :

  1. We can't inject the AngularJS modules on the fly. This loads files only when needed i.e. RequireJS only loads javascript files but it doesn't register the new angular modules and components in this new code


Pros :

  1. OcLazyLoad is used to load the dependency files and also to inject the AngularJS modules on the fly.
  2. Loading Js and Css files are effortless.

Cons :

  1. We can't maintain the dependency files structure.

So you can use Require.js to load dependencies between modules listed in code and OcLazyLoad to inject Angular module on fly . And for your question regarding angular itself on fly, I don't think you can do that in this case.