COMP6080
Web Front-End Programming
Javascript
In the web browser
Where to put your browser-based Javscript
Javascript is a programming language, that has two main uses:
- Javascript used to manipulate the DOM in a web browser (discussed in another lecture)
- Javascript used to write scripts with NodeJS (discussed in another lecture)
Today we are focusing on (1).
More specifically, what are the different ways you can include your Javascript in a page run by a web browser?
HOW code is included
Code can either be included inline (part of the page) or included via external link (URL to resource)
<script type="text/javascript">
const a = 1 + 2;
console.log(a);
</script>
<script type="text/javascript" src="mywork.js">
</script>
const a = 1 + 2;
console.log(a);
inline
external
mypage1.html
mypage2.html
mywork.js
HOW code is included
Linking javascript externally:
- Improvements performance when browser cache is utilised
- Reduces the time it takes for initial html document to be received (smaller file)
Placing Javascript inline:
- Avoids network requests (potentially costly) for script if file is not yet loaded
WHERE code is included
<html>
<head>
<!-- CAN INCLUDE IN HEADER -->
</head>
<body>
<!-- CAN INCLUDE IN TOP OF THE BODY -->
<!-- MOST OF YOUR PAGE -->
<!-- CAN INCLUDE IN BOTTOM OF THE BODY -->
</body>
</html>
Generally speaking you can either:
- Include in the <head> or at the top of <body> if you need your javascript to run prior to your DOM elements doing initial render
- Include at the end of <body> if you need do not need your javascript to run prior to your DOM elements initially rendering
We usually do (2)
COMP6080 - Javascript - In the browser
By haydensmith
COMP6080 - Javascript - In the browser
- 642