On-Demand JavaScript

You can use XMLHttpRequest (XHR: AJAX's engine) to pull JavaScript down to the client as needed. An alternative approach tested here is using the Document Object Model (DOM) to create a new <script> element, which grabs the script using the standard "src" attribute. An advantage of this is that you can cross domains with this approach, which is generally forbidden when using XHR.

Try these steps below, preferably in order.

  1. Click here to use a function from the additional script.
  2. Click here to pull in JavaScript file (extra.js) which was not included initially.
  3. Now try step #1 again. It works!
  4. Now try step #2 again. It can tell it doesn't need to load the script again!

See the On-Demand JavaScript page at AjaxPatterns.org for a more thorough treatment of this approach.