Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 593
edt Avatar asked Sep 15 '16 16:09

edt


People also ask

How do you load data into JavaScript?

In order to do that, you will need to: send an AJAX request in your javascript code. parse the request and send back the file via PHP. do your logic in Javascript when the request is responded.

How do I use document ready in JavaScript?

The ready() method is used to make a function available after the document is loaded. Whatever code you write inside the $(document ). ready() method will run once the page DOM is ready to execute JavaScript code.


1 Answers

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

Require.js

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

OcLazyLoad

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.

like image 199
Abhijeet Avatar answered Sep 26 '22 03:09

Abhijeet