How to Embed JavaScript Code in HTML File?
One of the first thing that you should learn when it comes to coding with JavaScript is surely embedding a JS Code to HTML File. In this brief tutorial, we will see 2 simple methods to achieve that. So let's get started :)
So in a nutshell, JavaScript can be added to your HTML file in two ways:
Internal JavaScript:
We can add JavaScript directly to our HTML file by writing the code inside the <script> tag. The <script> tag can be simply placed inside the <body> or the <head> tag.
External JavaScript:
- We can write JavaScript code in other file having an extension .js and after that we try to link the file inside the <head> tag of the HTML file in which we want to add this new code snippet.
- Another alternative is to add a full website URL that contains a js file called myScript.js: <script src=" myScript.js"></script>
- The js file can be inside a folder called js : <script src="/js/myScript.js"></script>
- We can also add a full website URL that contains a js file called myScript.js <script src="https://www.selfmadetechie.com/js/myScript.js"></script>
Are you wondering which method you should use?
It’s simple question. Well, I advise you to alter between the 2 methods: use the internal method if the script is short, otherwise separate it in another file.