Html script to js file

❮ HTML

Try it Yourself »


Definition and Usage

The src attribute specifies the URL of an external script file.

If you want to run the same JavaScript on several pages in a web site, you should create an external JavaScript file, instead of writing the same script over and over again. Save the script file with a .js extension, and then refer to it using the src attribute in the tags.

Example

Try it Yourself »

Old JavaScript examples may use a type attribute:

Demo JavaScript in Head

A Paragraph



Try it Yourself »



JavaScript in

In this example, a JavaScript function is placed in the section of an HTML page.

The function is invoked (called) when a button is clicked:

Example



Demo JavaScript in Body

A Paragraph


Try it Yourself »

Placing scripts at the bottom of the element improves the display speed, because script interpretation slows down the display.


External JavaScript

Scripts can also be placed in external files:

External file: myScript.js

function myFunction() {
  document.getElementById("demo").innerHTML = "Paragraph changed.";
}

External scripts are practical when the same code is used in many different web pages.

JavaScript files have the file extension .js.

To use an external script, put the name of the script file in the src (source) attribute of a


External References

An external script can be referenced in 3 different ways:

  • With a full URL (a full web address)
  • With a file path (like /js/)
  • Without any path

This example uses a full URL to link to myScript.js:

Example

Try it Yourself »

This example uses a file path to link to myScript.js:

This example uses no path to link to myScript.js:

You can read more about file paths in the chapter HTML File Paths.



Can we write HTML code in JS file?

JavaScript in or You can place any number of scripts in an HTML document.

How do I connect JavaScript and HTML?

Adding JavaScript into an HTML Document You can add JavaScript code in an HTML document by employing the dedicated HTML tag tag either inside the head of the HTML or at the end of the body.