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>

mkyong

Founder of Mkyong.com, passionate Java and open-source technologies. If you enjoy my tutorials, consider making a donation to these charities.

3 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
krunal
9 years ago

you are the best mkyound. good tutorials. thanks

ConfusedbyCode
12 years ago

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?

Avenida Gez
13 years ago

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