How to load JavaScript at runtime with jQuery

To increase the website performance and reduce the total file’s size return, you may consider to load JavaSript (.js) file when it’s required. In jQuery, you can use the $.getScript function to load a JavaScript file at runtime or on demand.

For example,


$("#load").click(function(){
	$.getScript('helloworld.js', function() {
  		$("#content").html('Javascript is loaded successful!');
	});
});

when a button with an Id of “load” is clicked, it will load the “helloworld.js” JavaScript file dynamically.

Try it yourself

In this example, when you clicked on the load button, it will load the “js-example/helloworld.js” at runtime, which contains a “sayhello()” function.


<html>
<head>

<script type="text/javascript" src="jquery-1.4.2.min.js"></script>

</head>
<body>
  <h1>Load Javascript dynamically with jQuery</h1>

<div id="content"></div>
<br/>

<button id="load">Load JavaScript</button>
<button id="sayHello">Say Hello</button>

<script type="text/javascript">

$("#load").click(function(){
  $.getScript('js-example/helloworld.js', function() {
     $("#content").html('
          Javascript is loaded successful! sayHello() function is loaded!
     ');
  });
});

$("#sayHello").click(function(){
  sayHello();
});

</script>
</body>
</html>

3 comments on “How to load JavaScript at runtime with jQuery

  1. Hi ,
    Thanks for this very educating post, i have just one addition though.. A question…
    How about when i load a Div or load content from an external file …

    how best can i use Javascript to handle clicks on that newly loaded div?

    Reply
  2. Hi, just a question
    Please let me know what happens if reloaded many times
    Do I have to delete it first, to reload?
    Thanks

    Reply

Leave a Comment

Your email address will not be published. Required fields are marked *