0% found this document useful (0 votes)
3 views17 pages

Client Side Scripting Deep Notes

Uploaded by

makoyeelias0753
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)
3 views17 pages

Client Side Scripting Deep Notes

Uploaded by

makoyeelias0753
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

CLIENT-SIDE SCRIPTING

Deep Study Notes

COU 07201: Web Designs and Hosting


Lecture 2 — Web Development Technologies
DIT | NTA Level 7 | Mr. Sebastian
Dar es Salaam Institute of Technology
■ Table of Contents

1. What is Client-Side Scripting?


2. How It Works — The Full Browser Cycle
3. Main Client-Side Scripting Languages
4. What Client-Side Scripts Are Used For
4.1 Form Validation
4.2 Enhancing Interactivity
4.3 Manipulating Page Content (DOM)
4.4 ActiveX Controls
5. Limitations of Client-Side Scripting
6. Client-Side vs Server-Side — Deep Comparison
7. JavaScript In Depth
7.1 How the Browser Executes JavaScript (JIT)
7.2 The DOM — Document Object Model
7.3 Events and Event Listeners
7.4 The Fetch API / AJAX
8. Security Implications
9. Real-World Code Examples
10. Quick-Revision Summary Table
11. Exam Practice Questions

COU 07201: Web Designs and Hosting | Client-Side Scripting Deep Notes | DIT NTA Level 7
1. What is Client-Side Scripting?

Client-side scripting refers to code that travels from the web server to the user's browser as
part of the HTML page download, and is then executed entirely inside the user's web
browser — not on the server. Once the file is delivered, the server's job is done; the browser
takes over completely.

■ Real-World Analogy
Think of a web server as a chef. In server-side scripting, the chef cooks the meal
fully and sends only the finished plate. In client-side scripting, the chef sends a
'meal kit' (HTML + script) and the customer's browser assembles and heats it. The
customer can stir the soup, add salt, or reheat it — all without calling the kitchen
again.

Key defining properties:


• Runs in the browser — Execution uses the browser's built-in JS engine (V8 in Chrome,
SpiderMonkey in Firefox).
• Downloaded with the page — Script code is embedded in or linked from the HTML file
the server sends.
• No extra server request needed — Once loaded, the script reacts to user actions
instantly.
• Stateless by default — State is lost when the page closes unless localStorage or
cookies are used.

■ Note
"Client-side scripting = code sent by the server but executed by the browser, enabling
interactive pages without repeated server contact."

COU 07201: Web Designs and Hosting | Client-Side Scripting Deep Notes | DIT NTA Level 7
2. How It Works — The Full Browser Cycle

Understanding the request-response cycle shows exactly where client-side scripting fits and
why it is fast.

Step 1 — User types URL


The browser sends an HTTP GET request to the web server.

Step 2 — Server responds


The server sends back an HTML file containing <script> tags or links to external .js files.

Step 3 — Browser parses HTML


The browser reads HTML top-to-bottom, builds the DOM tree. When it hits a <script> tag it
pauses and executes the script.

Step 4 — JavaScript engine runs


The browser's JIT compiler executes the script — attaching event listeners, modifying the
DOM, or setting timers.

Step 5 — User interacts


When the user clicks, types, or scrolls, JavaScript event handlers fire instantly — no server
involved.

Step 6 — Optional AJAX/Fetch


If new data is needed (e.g. search suggestions), the script sends a background HTTP
request and updates part of the page only.

■ Tip
Steps 1-3 involve the network (slow). Steps 4-5 are local (fast). Good web design offloads as
much interaction as possible to client-side scripts to keep pages feeling responsive.

COU 07201: Web Designs and Hosting | Client-Side Scripting Deep Notes | DIT NTA Level 7
3. Main Client-Side Scripting Languages

3.1 JavaScript
JavaScript (JS) is the only natively supported scripting language in all modern browsers.
Created in 1995 by Brendan Eich at Netscape, it has grown into one of the world's most
widely used languages.

Why JavaScript dominates:


• Supported by every modern browser — no plugins required.
• Standardised as ECMAScript (ES5, ES6, ES2020+) ensuring cross-browser
consistency.
• Massive ecosystem: React, Vue, jQuery, [Link], and millions of npm packages.
• Runs on the server too via [Link] — making JS a full-stack language.
• Asynchronous capabilities (Promises, async/await) allow non-blocking code.
• JIT-compiled — the browser compiles and optimises it at runtime for high performance.

3.2 VBScript
VBScript was Microsoft's Internet Explorer-only alternative to JavaScript, based on Visual
Basic syntax. It was never adopted by other browsers.

Feature VBScript JavaScript

Browser support Internet Explorer only All modern browsers

Created by Microsoft (1996) Netscape (1995)

Current status Obsolete — IE retired 2022 Actively developed (ES2024+)

Syntax style Visual Basic-like C-style (curly braces)

Server-side version None [Link]

Mobile support None Full support

■■ Warning
VBScript is dead — do not use it in any new project. Microsoft retired Internet Explorer in June
2022. All VBScript functionality is replaceable with JavaScript.

COU 07201: Web Designs and Hosting | Client-Side Scripting Deep Notes | DIT NTA Level 7
4. What Client-Side Scripts Are Used For

4.1 Form Validation


Form validation means checking user input before sending it to the server. Without it, the
server must receive bad data, reject it, and send the whole page back — a slow, wasteful
round trip.

Types of validation JavaScript can perform:


• Presence check — Is the field empty? 'Name is required.'
• Format check — Does the email contain '@'? Is the phone 10 digits?
• Range check — Is the age between 1 and 120?
• Match check — Does 'Password' equal 'Confirm Password'?
• Length check — Is the password at least 8 characters?
• Pattern check (Regex) — Does the postcode match a defined pattern?

■ Note
Scenario: A registration form asks for the user's age.
Without JS: Browser submits → server detects error → entire page reloads with error
message.
With JS: As cursor leaves the age field (blur event), JS instantly checks: is it a number? Is it
1-120? A red message appears immediately. The form never submits until valid.
Result: Better UX, less server load, faster error correction for the user.

4.2 Enhancing Interactivity


Interactivity means the page responds to user actions in real time — without reloading. This
transformed the web from static documents into a platform for full applications.

• Dropdown navigation menus that expand on hover or click


• Image carousels and sliders
• Modal (pop-up) dialogs for confirmations, logins, or media
• Accordion sections that expand and collapse
• Live search boxes that filter a list as you type
• Drag-and-drop interfaces (e.g. Kanban boards)
• Infinite scroll that loads more content automatically
• Animated buttons, progress bars, and loading spinners
• Interactive maps powered by the Google Maps JavaScript API
• Real-time chat interfaces using WebSockets

COU 07201: Web Designs and Hosting | Client-Side Scripting Deep Notes | DIT NTA Level 7
4.3 Manipulating Page Content (DOM Manipulation)
The Document Object Model (DOM) is the browser's in-memory tree of the HTML page.
JavaScript can read and modify this tree at any time, updating the visible page instantly —
no reload needed.

DOM Operation JavaScript Example

Change text [Link] = "New text";

Change CSS style [Link] = "red";

Hide/show element [Link] = "none";

Add new element [Link](newElement);

Remove element [Link]();

Change attribute [Link]("src","[Link]");

Update counter [Link] = ++count;

4.4 ActiveX Controls


ActiveX was a Microsoft technology for embedding interactive components (media players,
document viewers) into web pages. It ran with high system privileges and was IE-only.

■■ Warning
ActiveX is obsolete and dangerous.
Security risk: ActiveX controls ran with elevated privileges — malicious sites could execute
code on the user's PC.
Vendor lock-in: only worked in Internet Explorer, never supported by other browsers.
Modern replacements: HTML5 video/audio, WebAssembly, JavaScript APIs — all safer and
cross-browser.

COU 07201: Web Designs and Hosting | Client-Side Scripting Deep Notes | DIT NTA Level 7
5. Limitations of Client-Side Scripting

Understanding what client-side scripts cannot do is just as important as knowing what they
can. These limitations define where server-side scripting must step in.

Cannot access databases directly


Client scripts run inside the browser sandbox — no direct path to a database server. JS must
make an HTTP request to a server-side API, which queries the database and returns data.

■ Note
Example / Implication: JS cannot call MySQL directly. It calls /api/user?id=5; the server queries
MySQL and returns JSON.

Source code is visible to anyone


Because JavaScript is sent as plain text, any user can press Ctrl+U or open DevTools (F12)
and read the entire script. Minification makes it harder to read but cannot truly hide logic.

■ Note
Example / Implication: Never put database passwords, API secret keys, or authentication logic
in client-side JS.

Depends on the browser and its settings


The browser must support JavaScript and have it enabled. Corporate firewalls, privacy
extensions like NoScript, or screen readers may disable JS, breaking pages that rely on it
entirely.

■ Note
Example / Implication: Use progressive enhancement: core content should work without JS;
scripts add enhancements on top.

COU 07201: Web Designs and Hosting | Client-Side Scripting Deep Notes | DIT NTA Level 7
Device and performance limitations
Heavy JavaScript (complex animations, large data processing) consumes CPU and RAM on
the user's device. On low-end smartphones — common in East Africa — this makes pages
slow or unresponsive.

■ Note
Example / Implication: Offload heavy processing to the server, or use Web Workers for
long-running background JS tasks.

Cannot personalise content without a server


A client-side script cannot know who the user is, their account balance, or purchase history
— that data lives in a database. Personalisation always requires a server-side component.

■ Note
Example / Implication: E-commerce sites use server APIs to inject personalised data (e.g.
'Welcome back, Amina!').

Cross-Site Scripting (XSS) vulnerability


If a website inserts user input into the DOM without sanitising it, an attacker can inject
malicious JavaScript that runs in other users' browsers — stealing cookies or logging
keystrokes.

■ Note
Example / Implication: Always sanitise user data before DOM insertion. Use textContent, never
innerHTML with untrusted data.

COU 07201: Web Designs and Hosting | Client-Side Scripting Deep Notes | DIT NTA Level 7
6. Client-Side vs Server-Side — Deep
Comparison

Feature Client-Side Server-Side

Where it runs User's browser Web server

Languages JavaScript (mainly) PHP, Python, [Link], Ruby,


Java, C#

Interaction speed Instant (no network delay) Network + server processing


time

Database access No — must use an API Yes — direct access

Code visibility Visible (Ctrl+U, F12) Hidden from user

Personalisation Limited (needs API call) Full access to user data

Security level Lower (untrusted device) Higher (controlled environment)

Server load Minimal Handles all logic

Typical uses Validation, menus, animations Login, payments, DB queries

When code runs After page loads in browser Before page is sent to browser

■ Tip
Best practice: use both together. Client-side JS handles fast UI interactions. Server-side code
handles data, security, and business logic. This 'API-driven' architecture is how all modern web
apps are built.

COU 07201: Web Designs and Hosting | Client-Side Scripting Deep Notes | DIT NTA Level 7
7. JavaScript In Depth

7.1 How the Browser Executes JavaScript (JIT Compilation)


Modern browsers do not simply interpret JS line-by-line. They use a Just-In-Time (JIT)
compiler:
• Parse — Reads JS source and builds an Abstract Syntax Tree (AST).
• Compile — Converts AST to bytecode (intermediate representation).
• Optimise — Frequently executed ('hot') code paths are compiled to native machine
code.
• Execute — Native code runs directly on the CPU — extremely fast.
• Garbage Collect — Engine automatically frees memory from objects no longer in use.

7.2 The DOM — Document Object Model


The DOM is the browser's in-memory tree of the HTML page. Each HTML tag is a node; text
becomes text nodes; attributes become attribute nodes. JavaScript uses the DOM API to
read and change the page.

■ Real-World Analogy
The DOM is like a family tree. <html> is the great-grandparent. <head> and <body>
are its children. Paragraphs and divs are grandchildren. JavaScript can find any
family member by name, change their appearance, move them, or remove them.

7.3 Events and Event Listeners


JavaScript is event-driven: code runs in response to things that happen. The browser fires
events constantly — clicks, keypresses, page loads, network responses. Developers attach
event listeners to DOM elements to respond to them.

Event When It Fires

click User clicks an element

submit A form is submitted

keyup / keydown A keyboard key is pressed or released

input The value of an input field changes

mouseover / mouseout Mouse pointer enters or leaves an element

COU 07201: Web Designs and Hosting | Client-Side Scripting Deep Notes | DIT NTA Level 7
Event When It Fires

load The page or image has finished loading

DOMContentLoaded HTML fully parsed (before images load)

scroll User scrolls the page

focus / blur Input gains or loses focus

7.4 The Fetch API / AJAX


The Fetch API lets JavaScript send HTTP requests to a server in the background without
reloading the page. This is how modern single-page applications (SPAs) work.

1. User triggers an action (e.g. types in a search box).


2. JS calls fetch('/api/search?q=laptop') — sends a background HTTP GET.
3. Server processes the request and returns JSON data.
4. JS receives the response, parses the JSON, and updates the DOM.
5. User sees results — no page reload occurred.

■ Tip
AJAX (Asynchronous JavaScript and XML) was the original term using XMLHttpRequest
(XHR). The modern Fetch API is cleaner and uses Promises / async-await. Both achieve the
same goal: background server communication without page reload.

COU 07201: Web Designs and Hosting | Client-Side Scripting Deep Notes | DIT NTA Level 7
8. Security Implications

NEVER store secrets in client-side code


API keys, database passwords, and session tokens in JS files are readable by anyone. Store
secrets on the server; access them through authenticated server-side APIs only.

Validate on the server too


Client-side validation is for user experience, not security. An attacker can bypass all JS
validation by sending a raw HTTP request directly to the server. Always re-validate
server-side.

Sanitise DOM insertions — prevent XSS


Cross-Site Scripting (XSS) is the #1 web vulnerability. Use [Link] instead of
[Link] when inserting user data. For HTML, use a library like DOMPurify.

Avoid eval()
eval() executes a string as JS code. If that string contains user data, it is a critical security
hole. Avoid eval() entirely in production code.

Always use HTTPS


Without TLS encryption, an attacker on the same network can intercept and modify your
JavaScript files, injecting malicious code before the browser receives them.

Content Security Policy (CSP)


A CSP HTTP header tells the browser which JS sources are trusted. This prevents attackers
from injecting scripts from external malicious domains.

COU 07201: Web Designs and Hosting | Client-Side Scripting Deep Notes | DIT NTA Level 7
9. Real-World Code Examples

Form Validation — Age Check


function validateAge() {
var age = [Link]("age").value;
var msg = [Link]("ageError");
if (isNaN(age) || age < 1 || age > 120) {
[Link] = "Please enter a valid age (1-120).";
[Link] = "red";
return false; // Block form submission
}
return true;
}

DOM Manipulation — Click Counter


var count = 0;
[Link]("btn").addEventListener("click", function() {
count++;
[Link]("counter").textContent = count;
});

Toggle Show/Hide Section


function toggle() {
var el = [Link]("details");
[Link] = ([Link] === "none") ? "block" : "none";
}

Fetch API — Load Data Without Reloading


fetch("/api/products")
.then(function(response) { return [Link](); })
.then(function(data) {
[Link](function(product) {
var li = [Link]("li");
[Link] = [Link]; // Safe: textContent, not innerHTML
[Link]("list").appendChild(li);
});
})
.catch(function(err) { [Link]("Error:", err); });

COU 07201: Web Designs and Hosting | Client-Side Scripting Deep Notes | DIT NTA Level 7
10. Quick-Revision Summary Table

Concept Key Point Remember For Exam

Client-side scripting Runs in browser, not server Enables interactivity without


server contact

JavaScript Only universal browser language V8 (Chrome), SpiderMonkey


(Firefox)

VBScript Obsolete, IE only IE retired June 2022;


replaced by JS

Form validation Checks input before server send Client-side = UX; server-side
= security

DOM manipulation JS changes page structure in real textContent, querySelector,


time appendChild

Event listeners Code fires when user does click, submit, keyup, load,
something blur

Fetch / AJAX Background server communication No reload; updates DOM


with JSON data

ActiveX Old IE-only interactive controls Obsolete, insecure, never


cross-browser

Limitation: DB JS cannot query a database directly Must use a server-side API


endpoint

Limitation: visibility Source code readable by anyone Never put secrets in JS files

Limitation: devices Heavy JS slows low-end phones Use progressive


enhancement

XSS vulnerability Injected JS runs in victim's browser Sanitise input; use


textContent not innerHTML

COU 07201: Web Designs and Hosting | Client-Side Scripting Deep Notes | DIT NTA Level 7
11. Exam Practice Questions

1. Define client-side scripting and explain how it differs from server-side scripting. (4
marks)
Model Answer: Client-side scripting is code downloaded from the server with the HTML
page and executed by the user's browser. Server-side scripting runs on the web server
before the page is sent. Key differences: client-side is visible to the user, cannot access
databases directly, and provides instant interaction; server-side is hidden, has direct
database access, and handles security-critical tasks.

2. State TWO main client-side scripting languages and explain why one of them is now
obsolete. (3 marks)
Model Answer: JavaScript and VBScript. VBScript is obsolete because it only worked in
Internet Explorer, which Microsoft retired in June 2022. It was never adopted by other
browsers, making it impossible to use for modern cross-browser web development.

3. Explain the benefit of JavaScript form validation compared to server-side validation


only. (3 marks)
Model Answer: JavaScript validates input immediately in the browser, giving users
instant feedback without waiting for a server response. This improves user experience,
reduces unnecessary server load (invalid data is never sent), and speeds up error
correction.

4. List THREE limitations of client-side scripting and explain each briefly. (6 marks)
Model Answer: (i) Cannot access databases — client scripts have no direct path to a
database; a server-side API is required. (ii) Source code is visible — any user can read
the JavaScript using browser developer tools, so sensitive information cannot be hidden.
(iii) Device limitations — heavy scripts can slow pages on low-powered devices because
all processing happens on the user's hardware.

5. What is DOM manipulation? Give TWO examples of what JavaScript can change. (4
marks)
Model Answer: DOM manipulation is the use of JavaScript to modify the browser's
in-memory representation of the HTML page, updating the visible page without reloading.
Examples: (i) Changing the text of a paragraph element. (ii) Hiding or showing an element
by changing its CSS display property.

COU 07201: Web Designs and Hosting | Client-Side Scripting Deep Notes | DIT NTA Level 7
6. Why is it dangerous to store database credentials in a client-side JavaScript file? (2
marks)
Model Answer: JavaScript files are sent to and stored in the user's browser. Anyone can
view them using browser developer tools (F12). An attacker who finds credentials in a JS
file can directly access the database and steal or delete data.

7. Describe what happens when a user clicks 'Like' on a social media site. Include any
server communication. (5 marks)
Model Answer: (1) User clicks Like — a click event fires. (2) JS event listener updates the
like count in the DOM immediately for instant feedback. (3) In the background, the Fetch
API sends an HTTP POST to the server (e.g. POST /api/like?post=42). (4) The server
validates the session, updates the database, and returns a JSON response. (5) JS
updates the count with the confirmed server value. The page never reloaded throughout.

End of Notes — Client-Side Scripting | COU 07201 | DIT | NTA Level 7


Prepared for academic study. Cross-reference with your lecturer's slides and textbooks.

COU 07201: Web Designs and Hosting | Client-Side Scripting Deep Notes | DIT NTA Level 7

You might also like