Coding with JavaScript For Dummies
Book image
Explore Book Buy On Amazon

The most popular way to include JavaScript in HTML documents is by using the src attribute of the script element. A script element with a src attribute works exactly like a script element with JavaScript between the tags, except that if you use the src attribute, the JavaScript is loaded into the HTML document from a separate file. Here’s an example of a script element with a src attribute:

<script src="myScript.js"></script>

In this case, you would have a separate file, named myScript.js, that would reside in the same folder as your HTML document. The benefits of using external JavaScript files are that using them

  • Keeps your HTML files neater and less cluttered

  • Makes your life easier because you need to modify JavaScript in only one place when something changes or when you make a bug fix

Creating a .js file

Creating an external JavaScript file is similar to creating an HTML file or another other type of file. To replace the embedded JavaScript with an external JavaScript file, follow these steps:

  1. In Sublime Text, choose File→New File.

  2. Copy everything between from MyFirstProgram.html and paste it into your new .js file.

    Notice that external JavaScript files don’t contain

About This Article

This article is from the book:

About the book authors:

Chris Minnick is an accomplished author, trainer, and web developer who has worked on web and mobile projects for both small and major businesses. Eva Holland is an experienced writer and trainer who has designed and taught online, in-person, and video courses. They are cofounders of WatzThis?

This article can be found in the category: