Sunday, November 17, 2024
Google search engine
HomeLanguagesJavascriptHow .js file executed on the browser ?

How .js file executed on the browser ?

In this article, we will learn how a .js file is executed on the browser by using following multiple approaches. Refer to Server side and Client side Programming, for in-depth knowledge about Javascript.

How is .js is executed by the browser?

Every Web browser comes with a JavaScript engine that provides a JavaScript runtime environment. For example, Google Chrome uses the V8 JavaScript engine, developed by Lars Bak. V8 is an open-source JavaScript engine developed for Google Chrome and Chromium web browsers by The Chromium Project.

The browser’s built-in interpreter searches for <script> tag or .js  file linked with HTML file while loading a web page, and then interpretation and execution starts.

Approach 1: Using plain <script> tag:

Syntax: 

<script> js code</script>

Example: In this approach, we have written JavaScript code within the HTML file itself by using the <script> tag. This method is usually preferred when there is only a few lines of JS code are required in a Web project. The browser’s built-in interpreter searches for <script> tag in HTML file while loading a web page, and then interpretation and execution starts.

HTML




<!DOCTYPE html>
<html>
 
<body>
    <script>
        document.querySelector("body").innerHTML
            = "<h2>Welcome to neveropen</h2>";
             
        document.querySelector("body")
            .style.color = "green";
    </script>
</body>
 
</html>


Output:

Approach 2: Using <script src=””> with “src” Parameter:

Syntax: 

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

Parameters:

  • src: file path for the JavaScript file

To know more about file paths refer Path Name in File Directory.

Example: Below is the Javascript code from the previous example, we want to execute this code by following a different separate approach. We will create a separate file “app.js“, and put the code below in this “.js” file.

app.js

Now, we will use the below code to link the ‘.js‘ file with the HTML file. For this task, we will use a <script src=” “> tag where will we provide the file path of our .js file in the src parameter. In this way when our HTML file starts getting loaded in the browser then the browser’s built-in interpreter searches for <script> tag or .js  file linked with HTML file, and then interpretation and execution starts.

This approach is preferred when lots of lines of JavaScript code are required in a Web project, so we create a separate .js file and link that .js file to our HTML file using src parameter of <script> tag.
 

HTML




<!DOCTYPE html>
<html>
 
<body>
 
  <!-- Importing app.js file-->
  <script src="app.js"></script>
</body>
 
</html>


Output:

RELATED ARTICLES

Most Popular

Recent Comments