0% found this document useful (0 votes)
14 views69 pages

ITaS Lect03

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views69 pages

ITaS Lect03

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 69

Internet Technologies

and Services

JavaScript – part I
PhD, DSc Eng. Remigiusz Rajewski

April 25, 2024


Outline

Introduction

Definition

How it works?

Adding JavaScript to page

Script loading strategies

Comments

2
JavaScript – introduction

JavaScript (JS) is a lightweight interpreted (or just-in-time
compiled) programming language with first-class functions.

It is most well-known as the scripting language for Web pages,
however, many non-browser environments also use it, such as
Node.js, Apache CouchDB and Adobe Acrobat.

JavaScript is a prototype-based, multi-paradigm, single-
threaded, dynamic language, supporting object-oriented,
imperative, and declarative (e.g. functional programming)
styles.

3
JavaScript – introduction

JavaScript's dynamic capabilities include:

runtime object construction,

variable parameter lists,

function variables,
● dynamic script creation (via eval),
● object introspection (via for...in and Object utilities),

source-code recovery (JavaScript functions store their source text
and can be retrieved through toString()).

4
JavaScript – introduction

The standards for JavaScript are:

the ECMAScript Language Specification (ECMA-262),

the ECMAScript Internationalization API specification (ECMA-402).

Do not confuse JavaScript with the Java programming
language:

JavaScript is not "Interpreted Java",

both "Java" and "JavaScript" are trademarks or registered
trademarks of Oracle in the U.S. and other countries,

however, the two programming languages have very different syntax,
semantics, and use.
5
A high-level definition

JavaScript is a scripting or programming language that allows
you to implement complex features on web pages – every time
a web page does more than just sit there and display static
information for you to look at – displaying timely content
updates, interactive maps, animated 2D/3D graphics, scrolling
video jukeboxes, etc. – you can bet that JavaScript is probably
involved.

It is the third layer of the layer cake of standard web
technologies, two of which (HTML and CSS) we have covered
in much more detail in other parts of this Lecture.

6
A high-level definition

7
A high-level definition

HTML is the markup language that we use to structure and give
meaning to our web content, for example defining paragraphs,
headings, and data tables, or embedding images and videos in
the page.

CSS is a language of style rules that we use to apply styling to
our HTML content, for example setting background colors and
fonts, and laying out our content in multiple columns.

JavaScript is a scripting language that enables you to create
dynamically updating content, control multimedia, animate
images, and pretty much everything else. Okay, not everything,
but it is amazing what you can achieve with a few lines of
JavaScript code ;) 8
Example 1

Let's take a button as an example. We can mark it up using
HTML to give it structure and purpose:
<button type="button">Player 1: Bob</button>

9
Example 1

Then we can add some CSS into the mix to get it looking nice:
button {
font-family: "helvetica neue", helvetica, sans-serif;
letter-spacing: 1px;
text-transform: uppercase;
border: 2px solid rgb(200 200 0 / 60%);
background-color: rgb(0 217 217 / 60%);
color: rgb(100 0 0 / 100%);
box-shadow: 1px 1px 2px rgb(0 0 200 / 40%);
border-radius: 10px;
padding: 3px 10px;
10
cursor: pointer; }
Example 1

And finally, we can add some JavaScript to implement dynamic
behavior:
const button = document.querySelector("button");

button.addEventListener("click", updateName);

function updateName() {
const name = prompt("Enter a new name");
button.textContent = `Player 1: ${name}`;
}
11
What it can really do?

The core client-side JavaScript language consists of some
common programming features that allow you to do things like:

Store useful values inside variables. In the previous example for
instance, we ask for a new name to be entered then store that name
in a variable called name.

Operations on pieces of text (known as "strings" in programming). In
the above example we take the string "Player 1: " and join it to the
name variable to create the complete text label, e.g. "Player 1: Bob".

Running code in response to certain events occurring on a web page.
We used a click event in our example above to detect when the label
is clicked and then run the code that updates the text label.

And much more! 12
API

What is even more exciting however is the functionality built on
top of the client-side JavaScript language. So-called Application
Programming Interfaces (APIs) provide you with extra
superpowers to use in your JavaScript code.

APIs are ready-made sets of code building blocks that allow
a developer to implement programs that would otherwise be hard or
impossible to implement.

They do the same thing for programming that ready-made furniture
kits do for home building – it is much easier to take ready-cut panels
and screw them together to make a bookshelf than it is to work out
the design yourself, go and find the correct wood, cut all the panels to
the right size and shape, find the correct-sized screws, and then put
them together to make a bookshelf. 13
API categories

Browser APIs are built into your web browser, and are able to
expose data from the surrounding computer environment, or do
useful complex things.

Third party APIs are not built into the browser by default, and
you generally have to grab their code and information from
somewhere on the Web.

14
API categories

15
API categories – browser APIs

The DOM (Document Object Model) API allows to manipulate
HTML and CSS, creating, removing and changing HTML,
dynamically applying new styles to your page, etc. Every time
you see a popup window appear on a page, or some new
content displayed (as it was shown in example 1) for example,
that's the DOM in action.

The Geolocation API retrieves geographical information. This is
how Google Maps is able to find your location and plot it on a
map.

16
API categories – browser APIs

The Canvas and WebGL APIs allow you to create animated 2D
and 3D graphics.

Audio and Video APIs like HTMLMediaElement and WebRTC
allow you to do really interesting things with multimedia, such as
play audio and video right in a web page, or grab video from
your web camera and display it on someone else's computer.

17
API categories – third party APIs

The Twitter API allows you to do things like displaying your
latest tweets on your website.

The Google Maps API and OpenStreetMap API allows you to
embed custom maps into your website, and other such
functionality.

18
How it works?

What happens when we load a web page in a browser?

When we load a web page in a browser, we are running some code
(the HTML, CSS, and JavaScript) inside an execution environment
(the browser tab).

Therefore, this is like a factory that takes in raw materials (the code)
and outputs a product (the web page).

A very common use of JavaScript is to dynamically modify
HTML and CSS to update a user interface, via the DOM API.
Note that the code in your web documents is generally loaded
and executed in the order it appears on the page. Errors may
occur if JavaScript is loaded and run before the HTML and
CSS that it is intended to modify. 19
How it works?

20
Browser security

Each browser tab has its own separate bucket for running code
in (these buckets are called "execution environments" in
technical terms) – this means that in most cases the code in
each tab is run completely separately, and the code in one tab
cannot directly affect the code in another tab – or on another
website.

This is a good security measure – If this were not the case, then
pirates could start writing code to steal information from other
websites, and other such bad things.

Note: There are ways to send code and data between different
websites/tabs in a safe manner, but these are advanced
techniques that we won't cover in this lecture. 21
Browser security

When the browser encounters a block of JavaScript, it generally
runs it in order, from top to bottom. This means that you need
to be careful what order you put things in.

Let's return to the block of JavaScript in example 1:
const button = document.querySelector("button"); 1) selecting a button
button.addEventListener("click", updateName); 2) attaching an
event listener to it

function updateName() { 3) when the button


const name = prompt("Enter a new name"); is clicked, the
updateName()
button.textContent = `Player 1: ${name}`; code block is run
22
}
Browser security
● The updateName() code block (these types of reusable code
blocks are called "functions") asks the user for a new name,
then inserts that name into the button text to update the display.

If you swapped the order of the first two lines of code, it would
no longer work – instead, you'd get an error returned in the
browser developer console – Uncaught ReferenceError: Cannot
access 'button' before initialization. This means that the button
object has not been initialized yet, so we can't add an event
listener to it.

Note: This is a very common error – you need to be careful
that the objects referenced in your code exist before you
23
try to do stuff to them.
Interpreted vs compiled code

You might hear the terms interpreted and compiled in the
context of programming.

In interpreted languages, the code is run from top to bottom and the
result of running the code is immediately returned. You don't have to
transform the code into a different form before the browser runs it.
The code is received in its programmer-friendly text form and
processed directly from that.

Compiled languages on the other hand are transformed (compiled)
into another form before they are run by the computer. For example,
C/C++ are compiled into machine code that is then run by the
computer. The program is executed from a binary format, which was
generated from the original program source code.
24
Interpreted vs compiled code

JavaScript is a lightweight interpreted programming language.
The web browser receives the JavaScript code in its original
text form and runs the script from that.

From a technical standpoint, most modern JavaScript
interpreters actually use a technique called just-in-time
compiling to improve performance; the JavaScript source code
gets compiled into a faster, binary format while the script is
being used, so that it can be run as quickly as possible.

However, JavaScript is still considered an interpreted language,
since the compilation is handled at run time, rather than ahead
of time.
25
Server-side vs client-side

You might also hear the terms server-side and client-side
code, especially in the context of web development.

The client-side code is code that is run on the user's computer
– when a web page is viewed, the page's client-side code is
downloaded, then run and displayed by the browser.

The server-side code on the other hand is run on the server,
then its results are downloaded and displayed in the browser.

Examples of popular server-side web languages include PHP,
Python, Ruby, ASP.NET, and even JavaScript! JavaScript can
also be used as a server-side language, for example in the
popular Node.js environment. 26
Dynamic vs static

The word dynamic is used to describe both client-side
JavaScript, and server-side languages – it refers to the ability to
update the display of a web page/app to show different things in
different circumstances, generating new content as required.

Server-side code dynamically generates new content on the
server, e.g. pulling data from a database, whereas client-side
JavaScript dynamically generates new content inside the
browser on the client, e.g. creating a new HTML table, filling it
with data requested from the server, then displaying the table in
a web page shown to the user.

27
Dynamic vs static

The meaning is slightly different in the two contexts, but related,
and both approaches (server-side and client-side) usually work
together.

A web page with no dynamically updating content is referred to
as static – it just shows the same content all the time.

28
Adding JavaScript to page

JavaScript is applied to your HTML page in a similar manner to
CSS.

Whereas CSS uses <link> elements to apply external
stylesheets and <style> elements to apply internal stylesheets
to HTML, JavaScript only needs one friend in the world of
HTML – the <script> element.

29
Example 2 – internal JavaScript

Step 1: Create a new file apply-javascript.html and save it in a
directory.

Step 2: Open the file in your web browser and in your text
editor. You'll see that the HTML creates a simple web page
containing a clickable button.

Step 3: Next, go to your text editor and add the following in
your head just before your closing </head> tag:
<script>
// JavaScript goes here
</script>
30
Example 2 – internal JavaScript

Step 4: Now we'll add some JavaScript inside our <script>
element to make the page do something more interesting (add
the following code just below the // JavaScript goes here line)
document.addEventListener("DOMContentLoaded", () => {
function createParagraph() {
const para = document.createElement("p");
para.textContent = "You clicked the button!";
document.body.appendChild(para);
}

31
Example 2 – internal JavaScript

Step 4: Now we'll add some JavaScript inside our <script>
element to make the page do something more interesting (add
the following code just below the // JavaScript goes here line)
const buttons = document.querySelectorAll("button");

for (const button of buttons) {


button.addEventListener("click", createParagraph);
}
});

32
Example 2 – internal JavaScript

Step 5: Save your file and refresh the browser – now you
should see that when you click the button, a new paragraph is
generated and placed below.

Note: If your example doesn't seem to work, go through the
steps again and check that you did everything right. JavaScript
is case sensitive, and very fussy, so you need to enter the
syntax exactly as shown, otherwise it may not work.

33
Example 3 – external JavaScript

Step 1: First, create a new file in the same directory as your
sample HTML file. Call it script.js – make sure it has that .js
filename extension, as that's how it is recognized as JavaScript.

Step 2: Replace the current <script> element with the following:
<script src="script.js" defer></script>

34
Example 3 – external JavaScript

Step 3: Inside script.js add the following script:
function createParagraph() {
const para = document.createElement("p");
para.textContent = "You clicked the BUTTON!";
document.body.appendChild(para);
}
const buttons = document.querySelectorAll("button");
for (const button of buttons) {
button.addEventListener("click", createParagraph);
}
35
Example 3 – external JavaScript

Step 4: Save and refresh your browser, and you should see the
same thing!

It works just the same, but now we've got our JavaScript in an
external file.

This is generally a good thing in terms of organizing your code
and making it reusable across multiple HTML files.

Plus, the HTML is easier to read without huge chunks of script
dumped in it.

36
Inline JavaScript handlers

Note that sometimes you'll come across bits of actual
JavaScript code living inside HTML.

Inside JS file:
function createParagraph() {
const para = document.createElement("p");
para.textContent = "You clicked the BUTTON!";
document.body.appendChild(para);
}

Inside HTML file:
<button onclick="createParagraph()">Click me!</button>
37
Inline JavaScript handlers

This case has exactly the same functionality as in Example 2
and Example 3, except that the <button> element includes an
inline onclick handler to make the function run when the
button is pressed.

Please don't do this, however. It is bad practice to pollute your
HTML with JavaScript, and it is inefficient – you'd have to
include the onclick="createParagraph()" attribute on
every button you want the JavaScript to apply to.

38
Using addEventListener

Instead of including JavaScript in your HTML, use a pure
JavaScript construct.
● The querySelectorAll() function allows you to select all
the buttons on a page. You can then loop through the buttons,
assigning a handler for each using addEventListener().
The code for this is shown below:
const buttons = document.querySelectorAll("button");
for (const button of buttons) {
button.addEventListener("click", createParagraph);
}
39
Using addEventListener
● This might be a bit longer than the onclick attribute, but it will
work for all buttons – no matter how many are on the page, nor
how many are added or removed. The JavaScript does not
need to be changed.

40
Script loading strategies

There are a number of issues involved with getting scripts to
load at the right time.

Nothing is as simple as it seems! A common problem is that all
the HTML on a page is loaded in the order in which it appears.

If you are using JavaScript to manipulate elements on the page
(or more accurately, the Document Object Model), your code
won't work if the JavaScript is loaded and parsed before the
HTML you are trying to do something to.

41
Script loading strategies

In the previous examples, in the internal and external examples
the JavaScript is loaded and run in the head of the document,
before the HTML body is parsed.

This could cause an error, so we've used some constructs to
get around it.

In the internal example, you can see this structure around the
code:
document.addEventListener("DOMContentLoaded", () => {
// …
});
42
Script loading strategies

This is an event listener, which listens for the browser's
DOMContentLoaded event, which signifies that the HTML
body is completely loaded and parsed.

The JavaScript inside this block will not run until after that event
is fired, therefore the error is avoided.

In the external example, we use a more modern JavaScript
feature to solve the problem, the defer attribute, which tells
the browser to continue downloading the HTML content once
the <script> tag element has been reached.
<script src="script.js" defer></script>
43
Script loading strategies

In this case both the script and the HTML will load
simultaneously and the code will work.

Note: In the external case, we did not need to use the
DOMContentLoaded event because the defer attribute
solved the problem for us. We didn't use the defer solution for
the internal JavaScript example because defer only works
for external scripts.

44
Script loading strategies

An old-fashioned solution to this problem used to be to put your
script element right at the bottom of the body (e.g. just before
the </body> tag), so that it would load after all the HTML has
been parsed.

The problem with this solution is that loading/parsing of the
script is completely blocked until the HTML DOM has been
loaded. On larger sites with lots of JavaScript, this can cause a
major performance issue, slowing down your site.

45
async and defer

There are actually two modern features we can use to bypass
the problem of the blocking script – async and defer (used
before).
● Scripts loaded with the defer attribute will load in the order
they appear on the page. They won't run until the page content
has all loaded, which is useful if your scripts depend on the
DOM being in place (e.g. they modify one or more elements on
the page).

46
async and defer

Scripts loaded using the async attribute will download the script
without blocking the page while the script is being fetched.

However, once the download is complete, the script will
execute, which blocks the page from rendering. This means that
the rest of the content on the web page is prevented from being
processed and displayed to the user until the script finishes
executing.

You get no guarantee that scripts will run in any specific order. It
is best to use async when the scripts in the page run
independently from each other and depend on no other script
on the page.
47
async and defer

Here is a visual representation of the different script loading
methods and what that means for your page:

48
async and defer

We have the following script element:
<script async src="js/vendor/jquery.js"></script>
<script async src="js/script2.js"></script>
<script async src="js/script3.js"></script>

You can't rely on the order the scripts will load in. jquery.js may
load before or after script2.js and script3.js and if this is the
case, any functions in those scripts depending on jquery will
produce an error because jquery will not be defined at the
time the script runs.

49
async and defer

async should be used when you have a bunch of background
scripts to load in, and you just want to get them in place as
soon as possible.

For example, maybe you have some game data files to load,
which will be needed when the game actually begins, but for
now you just want to get on with showing the game intro, titles,
and lobby, without them being blocked by script loading.

50
async and defer
● Scripts loaded using the defer attribute will run in the order
they appear in the page and execute them as soon as the script
and content are downloaded:
<script defer src="js/vendor/jquery.js"></script>
<script defer src="js/script2.js"></script>
<script defer src="js/script3.js"></script>

We can be sure that jquery.js will load before script2.js and
script3.js and that script2.js will load before script3.js.

They won't run until the page content has all loaded, which is
useful if your scripts depend on the DOM being in place (e.g.
they modify one or more elements on the page). 51
async and defer
● async and defer both instruct the browser to download the
script(s) in a separate thread, while the rest of the page (the
DOM, etc.) is downloading, so the page loading is not blocked
during the fetch process.
● Scripts with an async attribute will execute as soon as the
download is complete. This blocks the page and does not
guarantee any specific execution order.
● Scripts with a defer attribute will load in the order they are in
and will only execute once everything has finished loading.

52
async and defer

If your scripts should be run immediately and they don't have
any dependencies, then use async.

If your scripts need to wait for parsing and depend on other
scripts and/or the DOM being in place, load them using defer
and put their corresponding <script> elements in the order
you want the browser to execute them.

53
Comments

As with HTML and CSS, it is possible to write comments into
your JavaScript code that will be ignored by the browser, and
exist to provide instructions to your fellow developers on how
the code works (and you, if you come back to your code after
six months and can't remember what you did).

Comments are very useful, and you should use them often,
particularly for larger applications.

54
Comments

There are two types of comments:

A single line comment is written after a double forward slash (//)
// I am a comment

A multi-line comment is written between the strings /* and */
/*
I am also
a comment
*/

55
Comments

So for example, we could annotate our last demo's JavaScript
with comments like so:
// Function: creates a new paragraph and appends it to the bottom of
the HTML body.
function createParagraph() {
const para = document.createElement("p");
para.textContent = "You clicked the BUTTON!";
document.body.appendChild(para);
}

56
Comments
/*
1. Get references to all the buttons on the page in an array format.
2. Loop through all the buttons and add a click event listener to
each one.
When any button is pressed, the createParagraph() function will be
run.
*/
const buttons = document.querySelectorAll("button");
for (const button of buttons) {
button.addEventListener("click", createParagraph);
} 57
Comments

Note: In general more comments are usually better than less,
but you should be careful if you find yourself adding lots of
comments to explain what variables are (your variable names
perhaps should be more intuitive), or to explain very simple
operations (maybe your code is overcomplicated).

58
Thinking like a programmer

One of the hardest things to learn in programming is not the
syntax you need to learn, but how to apply it to solve real-world
problems.

You need to start thinking like a programmer – this generally
involves looking at descriptions of what your program needs to
do, working out what code features are needed to achieve
those things, and how to make them work together.

This requires a mixture of hard work, experience with the
programming syntax, and practice – plus a bit of creativity. The
more you code, the better you'll get at it.
59
Operators

JavaScript operators allow us to perform tests, do math, join
strings together, and other such things.

Operator Name Example

+ Addition 10 + 9

- Subtraction 100 - 6

* Multiplication 3*4

/ Division 12 / 3
60
Operators

There are also some shortcut operators available, called
compound assignment operators.

For example, if you want to add a new number to an existing
one and return the result, you could do this:
let number1 = 1;
number1 += 2;

This is equivalent to:
let number2 = 1;
number2 = number2 + 2;

61
Comparison operators

When we are running true/false tests (for example inside
conditionals) we use comparison operators.
Operator Name Example

5 === 2 + 4 // false
Strict equality 'Chris' === 'Bob' // false
===
(is it exactly the same?) 5 === 2 + 3 // true
2 === '2' // false; number versus string
5 !== 2 + 4 // true
Non-equality 'Chris' !== 'Bob' // true
!==
(is it not the same?) 5 !== 2 + 3 // false
2 !== '2' // true; number versus string
62
Comparison operators

When we are running true/false tests (for example inside
conditionals) we use comparison operators.
Operator Name Example

6 < 10 // true
< Less than
20 < 10 // false
6 > 10 // false
> Greater than
20 > 10 // true

63
Variables

Variables are basically names for values (such as numbers, or
strings of text).
● We create a variable with the keyword let followed by a name
for your variable.

We can assign a value to your variable or constant with an
equals sign (=) followed by the value you want to give it.
let guessCount = 1;
let resetButton;
let randomNumber = Math.floor(Math.random() * 100) + 1;

64
Variables

Constants are also used to name values, but unlike variables,
we can't change the value once set.

In this case, we are using constants to store references to parts
of our user interface. The text inside some of these elements
might change, but each constant always references the same
HTML element that it was initialized with.
● We create a constant with the keyword const followed by
a name for the constant.
const guesses = document.querySelector(".guesses");
const lastResult = document.querySelector(".lastResult");
65
Functions

Functions are reusable blocks of code that we can write once
and run again and again, saving the need to keep repeating
code all the time.

This is really useful!!!

There are a number of ways to define functions, but for now
we'll concentrate on one simple type. Here we have defined a
function by using the keyword function, followed by a name,
with parentheses put after it. After that, we put two curly braces
({ }). Inside the curly braces goes all the code that we want to
run whenever we call the function.
66
Functions

Example function’s definition:
function checkGuess() {
alert("I am a placeholder");
}


When we want to run the code, we type the name of the
function followed by the parentheses:
checkGuess();

67
Text strings

Strings are used for representing text. From the previous slide,
in the following code, "I am a placeholder" is a string:
function checkGuess() {
alert("I am a placeholder");
}

You can declare strings using double quotes (") or single quotes
('), but you must use the same form for the start and end of a
single string declaration: you can't write "I am a placeholder'.

68
Text strings

We also declare strings using backticks (`).

Strings declared like this are called template literals and have
some special properties. In particular, we can embed other
variables or even expressions in them:
const name = "Mahalia";

const greeting = `Hello ${name}`;


This gives a mechanism to join strings together.
69

You might also like