CodingBison

While we can add scripts to an HTML page by adding the script in the HTML page itself, the recommended approach is to keep the script in a separate file. To do that we should use the "src" attribute of the <script> element to provide a path to the script file.

The recommendation to keep script file separate from the HTML file has several advantages. The first advantage is that we can use the same file in multiple HTML pages instead of having to provide the same code in multiple pages; thus, this provides a better code reusability. Code reusability can also make things more scalable. If you have thousands of pages on your site that use scripts, then you can keep all the scripts in a single file and manage it from there. If you want to change the behavior of an existing script, then all you have to do is change in one place -- this makes things more scalable.

Things To Remember
Keeping scripts and HTML separate provides better code reusability, scalability, and better code readability.

The second advantage with this approach is that we can also provide the URL of the script file located on an external server. Thus, if we have to include a remote file ("www.codingbison.com/library/foo.js"), then we can invoke that as: <script type="text/javascript" src="https://codingbison.com/library/foo.js">.

Yet another advantage is that it makes the HTML code less cluttered and thus, improves readability.

With that, let us see an example that sources an external JavaScript file. We start by creating a script file (let us say "kepler.js") that contains the JavaScript code; a JavaScript files has an extension of "js". We begin by providing the content of the file "kepler.js" below. Note that the script file holds pure JavaScript code without any HTML content.

 // Get a handle of the div element.
 var elem = document.getElementById("idDiv");

 // Write something to it. 
 elem.innerHTML +=  "NASA's Kepler Space Telescope has helped astronomers <br>";
 elem.innerHTML +=  "discover the first Earth-size planet located in a habitable zone <br>";
 elem.innerHTML +=  "in a distant Solar System. It is named  Kepler-186f. <br>";

Now that we have the JavaScript file ready to go, let us add it to an HTML page. We can include the JavaScript file as part of the script tag: <script type="text/javascript" src="./kepler.js">. We are assuming that the "kepler.js" file is in the same directory as that of the html file. Here is the HTML page.

 <!doctype html>
 <html>
 <head>
     <title> Adding Scripts to an HTML Page </title>
 </head>
 <body>
 <div id="idDiv"> </div>
 <script type="text/javascript" src="./kepler.js"></script>
 </body>
 </html>

When we load the page, we find that the page displays the text added to the <div> element.



Figure: Running JavaScript outside an HTML Page





comments powered by Disqus