How to run Javascript in the Browser
There are several ways to run JavaScript but the most popular is to run in inside an HTML in a web page and use a browser to run it.
Adding JavaScript to an HTML Document
Here are a couple of different way to run JavaScript directly in your browser.
HTML header
JavaScript can be added inside the header
page of the page via a script
tag:
<html>
<head>
<title>Webpage</title>
<script type="text/javascript">
console.log("here");
</script>
</head>
<body></body>
</html>
HTML body
JavaScript can also be added inside the body
of an HTML via a script
tag:
<html>
<head>
<title>Webpage</title>
</head>
<body>
<script type="text/javascript">
console.log("here");
</script>
</body>
</html>
External File
JavaScript can also be written inside a dedicated file and then "added" to the HTML page. Given a file named app.js
:
console.log('hello world');
... to include it in an HTML file:
<html>
<head>
<title>Webpage</title>
<script src="app.js"></script>
</head>
<body></body>
</html>
The files will need to reside side by side inside a folder (`my_project` in the example below):
my_project/
├── app.js
└── index.html
ES6 - import & export
As your project grows, the JavaScript code can be split across multiple file. In the example below, we'll use 2 JavaScript files:
export function House() {
this.width = 100;
this.length = 200;
}
function paint() {
...
}
function clean() {
...
}
export { paint, clean }
To include them both in an HTML file:
<html>
<head>
<title>Webpage</title>
<script type="module">
import { House } from "./my-script.js";
import { paint, clean } from "./second-script.js";
let house = new House();
</script>
</head>
<body></body>
</html>
Just like before, the files will need to reside side by side:
my_project/
├── my-script.js
├── second-script.js
└── index.html
ES10 - dynamic import with async Early days Google Chrome only
export const helloEvent = () => {
console.log('Hello World');
};
<html>
<head>
<title>Webpage</title>
<script type="text/javascript">
window.onload = function() {
document.getElementById('helloButton').addEventListener("click", async() => {
const module = await import('./myscript.js');
module.helloEvent();
});
}
</script>
</head>
<body></body>
</html>