Separating custom code in different file


 

Separating custom code in different file

In this jQuery tutorial,We separates custom code in the separate custom java script file

In this jQuery tutorial,We separates custom code in the separate custom java script file

Separating custom code in different file

We can separate custom code in the separate custom java script file. In this example ,we put the jQuery script in a separate file , which will save with ".js" extension. This ".js" file have all the jQuery scripting.

It's always a good practice to separate the JavaScript code into a separate file. So, beginners must understand the importance of separating the .js file into a different js file and then include it in your HTML page. Here are the benefits of separating the js file into a new file:

  • One place to manage all the js code
  • Include the js file when required, no need to modify the code in each html page
  • Performance of the application is also good as browser just download the file once and in subsequent request it uses from the cache.
  • Its a good programming practice

How to use the separate js file in HTML page?

You should create a separate js file and use the following code to include it in the HTML page:

<script type="text/javascript" src="custom.js"></script>

So, this is good and easy best practices of using the .js file in HTML page. In this example we have jQuery code in a different js file which we are including in our main HTML page and its working fine.

Here is the video of “Separate JavaScript file in jQuery HTML page”:

jqCustom.html

<html>
<head>
<title>The jQuery Example</title>
<script type="text/javascript" src="jquery-1.4.2.js">
</script>

<script type="text/javascript" src="custom.js"></script>
</head>
<body>
<div id="mydiv">
Click here to see a dialogue box.
</div>
</body>
</html>

custom.js

$(document).ready(function() {
  $("div").click(function() {
  alert("Hello Friends!");
  });
});

We can include "custom.js" file as :

<script type="text/javascript" src="custom.js"></script>

OUTPUT :

Download Source Code

Click here to see demo

Check more tutorial of jQuery at

Ads