Blog Archive

jQuery load javascript on demand, basically at runtime

Well if you specify all your JavaScript files in the HTML page then it gets loaded along with the page load. Now there are certain cases where based on the functionality on the page you may want to delay the loading until users makes a certain choice thereby reducing the initial load time and improving the website performance. In jQuery, you can use the $.getScript function to load a JavaScript file dynamically at runtime or on demand.

jquery load javascript on demand

In this example upon a button click we load a JavaScript function and then execute it.
<title>jQuery load JavaScript library on demand</title>

 rel="stylesheet" type="text/css" />

<script type="text/javascript">
 $(document).ready(function() {
  $('#myButton').click(function() {
<div id="myExample">
 <form id="myForm" action="">
   Dynamically load JavaScript library before calling a function

  <input id="myButton" type="button"
  value="This button will load a function dynamically before executing"/>
  <legend>See Result in this Section:</legend>
  <div id="myResults"></div>

JavaScript file that's loaded dynamically - app.js
function addSomeText() {
  .html("<b>Well I just loaded the JavaScript file app.js</b>" +
    " and then put some HTML content on this page!");

Please note: When loading JavaScripts dynamically with jQuery’s getScript it adds a cache busting parameter to the request URL causing the script to be loaded fresh each time. See screen below

jquery load javascript on demand