JavaScript in HTML
Here are a couple of different way to run JavaScript directly in your browser.
HTML header
<html>
<head>
<title>Webpage</title>
<script type="text/javascript">
console.log("here");
</script>
</head>
<body></body>
</html>
HTML body
<html>
<head>
<title>Webpage</title>
</head>
<body>
<script type="text/javascript">
console.log("here");
</script>
</body>
</html>
External File
Given a file named app.js, to include it in an HTML file named index.html:
<html>
<head>
<title>Webpage</title>
<script src="app.js"></script>
</head>
<body></body>
</html>
ES6 - import & export
In the example below, we'll use 2 JavaScript files:
export function House() {
this.width = 100;
this.length = 200;
}
my-script.js
function paint() {
...
}
function clean() {
...
}
export { paint, clean }
second-script.js
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>
ES10 - dynamic import with async Early days Google Chrome only
export const helloEvent = () => {
console.log('Hello World');
};
my-script.js
<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>
index.html
Top comments (0)