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.
- Create a JavaScript file with (.js) extension and write your function with the “export” keyword inside it
// external.js
export function hello(){
alert("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>
<html>
<head>
<title>CSS comments</title>
</head>
<script type="module">
import { hello} from './external.js';
</script>
<body>
</body>
</html>
4. Now, your javascript function has been accessed in an HTML file.
Advantages of external javascript files
- It separates HTML code and JavaScript code
- If you want to add multiple JavaScript files into HTML files. We have to use multiple Script tags
- If you have more than one external JavaScript file, then add it to the same web page to increase the performance of the webpage.