How to Call External Javascript Function From HTML

Call External Javascript Function From HTML

In this article, we will see, how to call an external javascript function from HTML.

Steps to call external JS Function from HTML

Follow these given steps to learn how to access external Javascript from an HTML file.

  1. Create a JavaScript file with (.js) extension and write your function with the “export” keyword inside it
// external.js
export function hello(){

2. Then HTML file with .html extension and write the HTML general syntax with <script> tag.
3. We should set the ‘type’ attribute to ‘module’ in the script tag. Then use the ‘import‘ keyword to call the function name and use the ‘from‘ keyword to locate the filename. Here, we should start the filename as ‘/‘ or ‘./‘.

// index.html
<!DOCTYPE html>
<title>CSS comments</title>
<script type="module">

import { hello} from './external.js';


4. Now, your javascript function has been accessed in an HTML file.

Advantages of external javascript files

  1. It separates HTML code and JavaScript code
  2. If you want to add multiple JavaScript files into HTML files. We have to use multiple Script tags
  3. If you have more than one external JavaScript file, then add it to the same web page to increase the performance of the webpage.

Leave a Reply