
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to include an external JavaScript inside an HTML page?
The HTML <script> tag is used for declaring a script within your HTML document. Through this, you can define client-side JavaScript. But, what if you want to add external JavaScript inside an HTML Page? Well, you can easily do that too using the src attribute of the <script> tag.
The following are the attributes of the <script> tag −
Attribute | Value | Description |
---|---|---|
async | async | Specifies that the script is executed asynchronously. |
charset | charset | Defines the character encoding that the script uses. |
defer | defer | Declares that the script will not generate any content. Therefore, the browser/user agent can continue parsing and rendering the rest of the page. |
src | URL | Specifies a URI/URL of an external script. |
type | text/JavaScript application/ecmascript application/JavaScript text/vbscript | Specifies the scripting language as a content-type (MIME type). |
For adding external JavaScript file, we will be using the src attribute −
Let’s see the HTML file first, which will include the source for the external file source.
Example
You can try to run the following code to include external JS in HTML. The HTML file is here, with a src to the JS file myscript.js.
<!DOCTYPE html> <html> <body> <h2>Alert Button</h2> <p> <External JavaScript file is myscript.js/p> <button type="button" onclick="sayHello()">Click</button> <script src="myscript.js"></script> </body> </html>
To use JavaScript from an external file source, you need to write all your JavaScript source code in a simple text file with the extension ".js" and then include that file as in the above structure i.e. <script src="myscript.js"></script>
Keep the following content in myscript.js file −
function sayHello() { alert("Hello World") }