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>
Any Java questions or problems? please post at this JavaNullPointer.com forum, see you there ~
[ Read More ] You can find more similar articles at jQuery Tutorials