JavaScript and HTML
getting started with JavaScript on a webpage
We can include Javascript in an HTML page in one of three ways:
JavaScript inline
One might see JavaScript placed inside HTML tags like this:
...where the value of the onClick
attribute would contain Javascript!
We will see this later in React when HTML takes on the form of something called "JSX" ;)
JavaScript encapsulated
A more contained form of JavaScript would enter via a <script>
tag in an HTML file:
Yet, this sets us up to use that piece of code in that page and only that page - not very friendly for reuse!
JavaScript from an external file
So, even better, we could place JavaScript in a file like this:
Then, we would load the file by placing an src
attribute in the <script>
tag instead:
This makes for a more modular approach; then, we could even add files from other sources like such:
With this, we can reuse code more easily and keep the HTML structure clean and clear!
Note two things:
the order of the
<script>
tags does matter:if
thirdpartycode2
depends onthirdpartycode1
thirdpartycode1
should appear higher up in the HTML
in older HTML, the
<script>
tag might have the optionaltype
attribute, which has become optional
JavaScript deferred
If a <script>
tag has to appear in the <head>
tag, we can use the defer
keyword:
this ensures that the rest of the HTML file gets loaded before the execution of this head script!
Last updated