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.
<html>
<head>
<title>jQuery load JavaScript library on demand</title>

<link
 href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css"
 rel="stylesheet" type="text/css" />

<script
 src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"
 type="text/javascript"></script>
<script
 src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"
 type="text/javascript"></script>
<script type="text/javascript">
 $(document).ready(function() {
  
  $('#myButton').click(function() {
       
   $.getScript('app.js',function(){
    addSomeText();
   });
      
  });
     
 });       
    </script>
</head>
<body>
<div id="myExample">
 <form id="myForm" action="">
 <fieldset>
  <legend>
   Dynamically load JavaScript library before calling a function
  </legend>

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

JavaScript file that's loaded dynamically - app.js
function addSomeText() {
 
 $("#myResults")
  .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

No comments:

Post a Comment

NO JUNK, Please try to keep this clean and related to the topic at hand.
Comments are for users to ask questions, collaborate or improve on existing.