JavaScript-Adding JavaScript to a Web Page

Gerald Clark
3 min readMay 4, 2024

I’ve gone ahead and created a new file within my file tree in VSCode. I called it “Chapter2” and added a HTML file called index.html. Remember, typing “doc” then TAB will auto-populate your html file with the boiler plate code.

Lets add some JS to this web page.

First I simply added a h1 that says “Hello There” within the body tags.

This is just so I can see something on the web page. Not mandatory.

So we can add JavaScript to a webpage anywhere between the head tags or the body tags. For example,

Right beneath the title tags I’ve added this line of code between these script tags. The alert() simply causes a quick pop up to appear when you open the web page and the message should say “Hello World!”

This is all good, but later on I wont be adding JS within the head tags. This can cause page loading issues later. Instead I want to add the JS in the body section at the bottom after all the html.

So this is fine when you are only going to write 1 line of code within the html file, but we could make this better by externalizing the JS and putting it in its own file then just link to that file from the html. For example,

I’ve created a .js file called sandbox in the file tree within my Chapter2 file.

I simply added the alert(“sup!”); line in the sandbox.js file.

To link this file to the html I had to make my script tag and then just link it by saying src="sandbox.js" like so…

If I run the html with Live Server now, this does the exact same thing as before. Our code is just cleaner and more organized now.

Thats basically all there is to it! In the next article I’ll go over the browser console a bit and try to de-mystify it! See ya there!

--

--