0% found this document useful (0 votes)
38 views62 pages

Model 1-2

The document provides an overview of web application development, detailing web technologies, frontend and backend development, and key concepts such as responsive design and RESTful APIs. It covers core technologies like HTML, CSS, and JavaScript for frontend, as well as server, application logic, and databases for backend. Additionally, it discusses internet protocols, HTML5 features, and form elements essential for creating interactive web pages.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views62 pages

Model 1-2

The document provides an overview of web application development, detailing web technologies, frontend and backend development, and key concepts such as responsive design and RESTful APIs. It covers core technologies like HTML, CSS, and JavaScript for frontend, as well as server, application logic, and databases for backend. Additionally, it discusses internet protocols, HTML5 features, and form elements essential for creating interactive web pages.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 62

Web Application Development

Web Technology
Web Technology refers to the various tools and techniques that are utilized in the process
of communication between different types of devices over the Internet. A web browser is
used to access web pages. Web browsers can be defined as programs that display text,
data, pictures, animation, and video on the Internet. Hyperlinked resources on the World
Wide Web can be accessed using software interfaces provided by Web browsers.

Web Technology can be Classified into the Following Sections:


•World Wide Web (WWW): The World Wide Web is based on several different
technologies: Web browsers, Hypertext Markup Language (HTML), and Hypertext Transfer
Protocol (HTTP).

•Web Browser: The web browser is an application software to access and


interact World Wide Web. It provides an interface between the server and the client,
sending requests to the server for web documents and services.

•Web Pages: A webpage is a digital document that is linked to the World Wide Web and
viewable by anyone connected to the internet who has a web browser.
•Web Server: A Web server is a program which processes the network requests of the users
and serves them with files that create web pages. This exchange takes place using Hypertext
Transfer Protocol (HTTP).

•Web Development: Web development refers to the building, creating, and maintaining of
websites. It includes aspects such as web design, web publishing, web programming, and
database management. It is the creation of an application that works over the internet, i.e.,
websites
Web Application Development can be Classified into Two Ways:

•Frontend Development: The part of a website that the user interacts with directly is
termed as front end. It is also referred to as the ‘client side’ of the application

Core Technologies in Frontend Development

1.HTML (HyperText Markup Language):


1. The structure of a webpage.
2. Defines elements like headings, paragraphs, links, images, and forms.

2.CSS (Cascading Style Sheets):


1. Controls the visual presentation of HTML elements.
2. Handles layout, colors, fonts, responsiveness, and animations.

3.JavaScript:
1. Adds interactivity to web pages.
2. Used for features like dropdowns, form validation, sliders, and dynamic content
updates.
Key Concepts

•Responsive Design: Ensuring a website looks good on all devices (mobile, tablet,
desktop).
•Accessibility (a11y): Making the web usable for people
•Cross-Browser Compatibility: Ensuring functionality across different browsers
(Chrome, Firefox, Safari, etc.).
•Single Page Applications (SPA): Apps that load a single HTML page and update
content dynamically without refreshing.
Backend Development: The Backend is the server side of a website. It is the part of the website
that users cannot see or interact with. It is the portion of software that does not come in direct
contact with the users. It is used to store and arrange data.

Core Components of Backend Development


1.Server:
1. Handles client requests and sends responses.
2. Can be configured using languages like PHP, Node.js, Python, Java, or Ruby.
2.Application (Business Logic):
1. Contains the core functionality of your application.
2. Processes requests, applies logic, handles authentication, etc.
3.Database:
1. Stores and manages data (e.g., user information, posts, orders).
2. Examples: MySQL, PostgreSQL, MongoDB, SQLite.
Common Backend Languages
•PHP – Popular for web apps (e.g., WordPress, Laravel).
•Node.js – JavaScript on the server side.
•Python – Used with frameworks like Django and Flask.
•Java – Common in enterprise applications.
•Ruby – Often used with Rails.

Key Concepts
•RESTful APIs and GraphQL for communication between frontend and backend.
•Authentication & Authorization – Managing user access and permissions.
•CRUD Operations – Create, Read, Update, Delete data.
•Server-Side Rendering (SSR) – Rendering content on the server before sending it to the
browser.
Protocols
Internet protocols are a set of rules that allow computers and other devices to
communicate over the Internet. These protocols ensure that data is sent, received, and
understood correctly between different systems. There are many types of internet
protocols, each serving a specific purpose, such as transferring files, sending emails, or
securing data. Understanding these protocols is important for making the internet work
efficiently and securely

Working of Internet Protocol


Step by step working of internet protocol:
•Dividing Data into Packets: When you send information over the internet, IP split it
into small parts called packets. Each packet contains a piece of the data and the
address of where it needs to go.

•Addressing: Every device connected to the internet has its own IP address. This
address helps identify where the data is being sent from and where it should be
delivered.

•Routing the Packets: As the packets travel across the internet, they pass through
several devices called routers. These routers help direct the packets toward the correct
destination, like how mail is sorted at different post offices.
•Reassemble the Data: Once all the packets arrive at the destination, they are put back
together to recreate the original message or file.

•Handling Missing Packets: If some packets don’t arrive, the system can request that
they be sent again, making sure the complete data is received.
Types of Internet Protocol
Internet Protocols are of different types having different uses. These are mentioned below:
1.TCP/IP(Transmission Control Protocol/ Internet Protocol)

2.SMTP(Simple Mail Transfer Protocol)

3.PPP(Point-to-Point Protocol)

4.FTP (File Transfer Protocol)

5.SFTP(Secure File Transfer Protocol)

6.HTTP(Hyper Text Transfer Protocol)

7.HTTPS(HyperText Transfer Protocol Secure)

8.TELNET(Terminal Network)

9.POP3(Post Office Protocol 3)

10.IPv4

11.IPv6
HTML5
Comparison between HTML and
HTML5
HTML  HTML5
 It didn’t support audio and video without the  It supports audio and video controls with the
use of flash player support. use of <audio> and <video> tags.
 It uses SQL databases and application cache
 It uses cookies to store temporary data.
to store offline data.
 Allows JavaScript to run in the background.
 Does not allow JavaScript to run in the
This is possible due to JS Web worker API in
browser. HTML5.
 Vector graphics are possible in HTML with the
 Vector graphics are additionally an integral
help of various technologies such as VML,
part of HTML5 like SVG and Canvas.
Silver-light, Flash, etc.
 It does not allow drag and drop effects.  It allows drag and drop effects.
 Not possible to draw shapes like circle,  HTML5 allows to draw shapes like circle,
rectangle, triangle etc. rectangle, triangle etc.
 It supported by all new browser like Firefox,
 It works with all old browsers.
Mozilla, Chrome, Safari, etc.
 It is almost impossible to get true  One can track the GeoLocation of a user easily
GeoLocation of user with the help of browser. by using JS GeoLocation API.
HTML5 is the fifth version of Hypertext Markup Language (HTML), a standard language
used to structure webpages. It defines how content on a webpage should
be structured and displayed. Here are some key points of HTML5
•Multimedia Support: Embeds audio and video without plugins.

•New Form Controls: Includes input types like date and email.

•Web Storage: Stores data offline for better performance.

•Semantic Elements: Uses tags like <header> and <footer> for better structure.

•Improved Performance: Faster and more efficient, especially on mobile.

New Added Elements in HTML 5

HTML5 introduced several new elements that help structure a webpage better and make it more
interactive. These elements not only improve the design but also make the code more readable
and accessible. Here are some key elements of HTML5:
Semantic Structure Elements
Before HTML5, developers mainly used <div> and <span> elements for layout and styling. These tags do not describe
their content. Semantic elements, however, provide meaningful tags to describe different parts of a web page.

1. <header>
Purpose: Represents introductory content or navigation links.
• Common Uses:
• Website logo
• Page title
• Navigation menus
• Can be used in: the <body> or inside sections like <article> or <section>
• Example
<header>
<h1>Issha Hair Clinic</h1>
<nav>
<a href="/">Home</a>
<a href="/services">Services</a>
</nav>
</header>
2. <nav>

 Purpose: Defines navigation links to other parts of the website or page.


 Important for: Screen readers to quickly find main navigation.

Example

<nav>
<ul>
<li><a href="/about">About Us</a></li>
<li><a href="/contact">Contact</a></li>
</ul>
</nav>
3. <main>
• Purpose: Represents the main content of the document.
• Important Rule: There should be only one <main> per page.
• Excludes: headers, footers, sidebars, etc.

• Example

<main>
<h2>Our Hair Treatments</h2>
<p>We offer a range of solutions for hair restoration...</p>
</main>

4. <section>
• Purpose: Represents a thematic group of content, usually with a heading.
• Good for: Grouping related content.
• Example
<section>
<h2>Patient Testimonials</h2>
<p>"Excellent service!" - Anil</p>
</section>
5. <article>
• Purpose: Represents a self-contained piece of content that can stand alone.
• Examples: Blog post, news article, forum post.
• Example
<article>
<h2>5 Tips to Prevent Hair Loss</h2>
<p>Hair loss is a common issue, but with the right care...</p>
</article>

6. <aside>
• Purpose: Contains content that is indirectly related to the main content.
• Examples: Sidebars ,Ads ,Related links, html Copy Edit
• Example
<aside>
<h3>Related Services</h3>
<ul>
<li><a href="/scalp-treatment">Scalp Treatment</a></li>
</ul>
</aside>
7. <footer>
• Purpose: Defines the footer for a document or section.
• Common Uses:
Copyright
Contact info
Site map

Example

\<footer>
<p>&copy; 2025 Issha Hair Clinic. All rights reserved.</p>
</footer>

8. <figure> and <figcaption>


• Purpose: Used to group media (images, illustrations, charts) with a caption.
• Good for: Descriptive images or media elements.
• Example
<figure>
<img src="hair-growth-before-after.jpg" alt="Hair growth result">
<figcaption>Before and After Hair Treatment</figcaption>
</figure>
What is a Form in HTML?
 An HTML form is a section of a document that contains interactive controls (like text fields,
checkboxes,
buttons, etc.) to collect user input.
 In HTML, the <form> element is used to collect user input. It acts as a container for different types
of input elements
like text fields, checkboxes, radio buttons, submit buttons, etc.

Basic Syntax:
<form action="submit.php" method="post">
<!-- input fields go here -->
</form>

Important Form Attributes:


Attribute Description
The URL where the form data is sent (usually to a server-side
action
script).
HTTP method: "get" (visible in URL) or "post" (more secure for
method
sending data).
How the form data should be encoded. Used with file uploads.
enctype
(e.g., multipart/form-data)
target Specifies where to display the response (e.g., _self, _blank)
Form Submission Methods
➤ GET Method:
 Appends form data to the URL.
 Visible to users (not secure).
 Used for search queries or non-sensitive data
 Example
<form action="search.php" method="get">

➤ POST Method:
• Sends form data in the HTTP request body (not in URL).
• More secure than GET.
• Suitable for login forms, registrations, uploads.
• Example
<form action="register.php" method="post">
Form Elements
HTML forms support a wide variety of controls:

Element Purpose
Single-line input (text, email,
<input>
password, etc.)
<textarea> Multi-line text input
<select> / <option> Dropdown lists
<button> / <input type="submit"> Form submission
<label> Text label for input fields
<fieldset> / <legend> Group related fields

Form Validation (Client-side)


HTML5 provides built-in input validation:
Attribute Purpose
required Makes the field mandatory
minlength,
Length restrictions
maxlength
pattern Regex pattern matching
type Automatically validates format (e.g., email, url)
Example:-
<input type="email" name="email" required>
HTML Input Element has various types that play an important role in creating HTML
Forms, and the element is efficient in collecting user data and adding interactivity to web pages.
These elements provide the feature to create an interactive web page. In the Input Element, there is
an attribute type having different values that help to create the form according to the requirements
of the web page. The default value of type is "text" in the input element

 In HTML, the input element is used to create form controls that allow users to enter data. The
type attribute of the input element defines the kind of data that can be entered or selected.

 The type attribute tells the browser what kind of input field to display and how to validate or
process the data entered by the user.

 Textual Inputs
• text – Single-line text input
• password – Password input (characters hidden)
• email – Validates for a valid email format
• url – Validates for a valid URL format
• tel – Input for a telephone number (no format enforcement)
• search – Designed for search fields (can style differently)
 Numeric Inputs
• number – Input for numeric values (with min, max, step)
• range – Slider control for numeric range

 Date & Time Inputs


• date – Date picker
• month – Month picker
• week – Week picker
• time – Time picker
• datetime-local – Date and time picker (without timezone)

 Choice Inputs
• checkbox – Checkbox (multiple selection)
• radio – Radio button (single selection within a group)
 File & Media Inputs
• file – File upload
• image – Submit button with an image as input
• button – Generic button
• submit – Submits the form
• reset – Resets the form
• hidden – Hidden input field (not visible to user)
• color – Color picker
Media Elements in web development refer to HTML elements that allow developers
to embed and control multimedia content such as audio and video within web pages.
These elements make it easy to include rich media without relying on third-party plugins
like Flash.

The Main Media Elements in HTML5:

 <audio> Element
• The <audio> element in HTML5 is used to embed audio content (like music,
podcasts, voice notes, etc.) directly into a web page. It allows browsers to play sound
without any third-party plugins (like Flash), making it simpler and more efficient for
developers to include audio.
• Used to embed audio content.
• Can play formats like MP3, WAV, and Ogg.
• Syntax
<audio src="song.mp3" controls></audio>
• Attributes:
i. src: Specifies the audio file path.
ii. controls: Displays audio controls (play, pause, volume).
iii. autoplay: Starts playing automatically.
iv. loop: Repeats the audio.
v. muted: Starts audio muted.

• Supported Audio Formats:


Format MIME Type Supported Browsers
1. MP3 audio/mpeg All major browsers
2. OGG audio/ogg Firefox, Chrome, Opera
3. WAV audio/wav Most browsers
 Key Benefits of <audio> in HTML5:
1. No plugins required — native to the browser.
2. Customizable using JavaScript.
3. Mobile-friendly.
4. Efficient for streaming or downloading audio content.

 Example
<audio controls>
<source src="audiofile.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
<video> Element
• The <video> element in HTML5 is used to embed video files directly into a web page.
It allows browsers to play video content (like movies, tutorials, or clips) without
needing third-party plugins like Flash.
• Used to embed video content.
• Supports formats like MP4, WebM, and Ogg.
• Syntax
<video src="movie.mp4" controls></video>
This line will embed the video and provide basic video player controls such as play, pause, volume, and fullscreen.
• Attributes:
1. src: Specifies the video file.
2. controls: Displays video controls.
3. autoplay: Starts automatically.
4. loop: Repeats the video.
5. muted: Starts muted.
6. poster: Image shown before the video starts

Example
<video width="320" height="240" controls>
<source src="videofile.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
Advanced HTML5
What is Canvas in HTML5?
 The <canvas> element in HTML5 is a drawing surface that allows you to draw graphics
via JavaScript. It provides a bitmap-based, scriptable space where you can render
shapes, images, text, and animations on the fly. It is commonly used in games, data
visualization, simulations, and real-time graphics rendering.

 Bitmap
• A bitmap (or raster image) is a grid of pixels, where each pixel represents a single point
in the image.
• Each pixel stores information about color (using RGB, RGBA, etc.).
• The image’s resolution is defined by the number of pixels (e.g., 800x600 = 800 pixels
wide and 600 pixels high).

 Basic Syntax
<canvas id="myCanvas" width="400" height="300">
Your browser does not support the HTML5 canvas tag.
</canvas>
• This creates a blank canvas that is 400x300 pixels in size.
• The content between the <canvas> tags is fallback content (displayed if the browser doesn’t
support canvas).
• By default, a canvas has no border and no visible content unless you draw on it with JavaScript.

 Accessing the Canvas Context


• To draw on the canvas, you need to get its rendering context using JavaScript:
1. const canvas = document.getElementById('myCanvas');
2. const ctx = canvas.getContext('2d'); // Get 2D drawing context
• ctx is the context object, which gives access to all the drawing methods.

 Advanced Features
• Paths and curves: Use beginPath(), lineTo(), bezierCurveTo(), etc.
• Transformations: Rotate, scale, and translate graphics.
• Image manipulation: Access individual pixels using getImageData() and putImageData().
• Animations: Combine with requestAnimationFrame() for smooth rendering.
• Hit detection: You must write custom code to detect mouse interaction, as canvas does not have
DOM elements.

Advantages of Canvas
•High-performance rendering, especially for dynamic or frequently changing visuals.
•Great for complex animations, games, and real-time updates.
•Gives full control over every pixel.

Limitations
•Canvas is not DOM-based: Once something is drawn, it's part of the bitmap and can’t be directly
interacted with.
•Not accessible by screen readers (unless managed separately).
•Harder to manage interactivity compared to SVG.
•Not resolution-independent — scaling might result in blur.
Example
<!DOCTYPE html>
<html>
<head>
<title>Draw Circle on Canvas</title>
</head>
<body>
<h2>Circle Drawing on Canvas</h2>
<canvas id="myCanvas" width="300" height="300" style="border:1px
solid #000000;"></canvas>

<script>
// Get the canvas element by its ID
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");

// Draw a circle
ctx.beginPath();
ctx.arc(150, 150, 70, 0, 2 * Math.PI); // arc(x, y, radius, startAngle,
endAngle)
ctx.stroke(); // Draw the circle outline
</script>
</body>
</html>
HTML SVG
 SVG stands for Scalable Vector Graphics. It defines vector-based graphics in XML format. SVG
graphics do not lose any quality when zoomed or resized, and every element and attribute in
SVG files can be animated

 SVG is used within HTML to draw shapes like circles, rectangles, lines, and even complex
illustrations such as logos, charts, and animations. Unlike raster images (like JPG or PNG), SVGs
are resolution-independent, meaning they look sharp on all screen sizes and resolutions

 You can either:


1. Embed SVG code directly inside an HTML document, or
2. Reference an external .svg file using an <img>, <object>, or <iframe> tag.

 Vector graphics are a flexible and scalable way to create images using mathematical equations
and geometric shapes, unlike pixel-based raster graphics. This method ensures that images
maintain high quality and sharpness at any size, making them ideal for logos, illustrations, and
other designs
Terminologies Related to Vector Graphics
•Mathematical Representation: Vector graphics represent object shapes and trajectories using
mathematical calculations. These formulas determine element position, size, and properties.

•Scalability: Scalability is a vector graphics advantage. Vector images are perfect for logos, icons,
and illustrations because they resize without losing quality.
•Editing Flexibility: Editing vector graphics is simple. Software like Adobe Illustrator or open-
source Inkscape may change vector objects' forms, colors, and characteristics.

•File Formats: Common file formats for vector graphics include SVG (Scalable Vector
Graphics), AI (Adobe Illustrator), and EPS (Encapsulated PostScript).

•Use Cases: Vector graphics are utilized in logos, typography, illustrations, and maps.

 The advantages of using SVG over other image formats (like JPEG and GIF) are:
1. SVG images scale without losing quality, making them perfect for responsive designs.

2. SVG files are often smaller than bitmap images, reducing load times.

3. SVG images can be edited easily with text editors, allowing for quick changes.

4. SVG content is accessible to screen readers, enhancing web accessibility.

5. SVG supports CSS and JavaScript animations, allowing for interactive and dynamic graphics
Common SVG Elements

• Tag Description
• <svg> The root container
• <rect> Draws a rectangle
• <circle> Draws a circle
• <ellipse> Draws an ellipse
• <line> Draws a straight line
• <polyline> Series of connected lines
• <polygon> Closed shape with multiple sides
• <path> Draws complex shapes/curves
• <text> Adds text to the SVG

• In SVG (Scalable Vector Graphics), attributes are used to define the appearance and behavior of
SVG elements such Attributes control things like position, size, color, stroke, and interactivity.
 Basic Syntax Example

<!DOCTYPE html>
<html>
<body>
<h2>SVG Circle Example</h2>
<svg width="200" height="200">
<circle cx="100" cy="100" r="80" stroke="black" stroke-width="3" fill="red" />
</svg>
</body>
</html>

 Explanation:
• <svg>: The container for SVG graphics.
• width, height: Dimensions of the canvas.
• <circle>: A shape element.
• cx and cy: X and Y coordinates of the center.
• r: Radius of the circle.
• stroke: Border color.
• stroke-width: Thickness of the border.
• fill: Inside color.
Limitations
Not ideal for complex photographic images.
More complex shapes can increase file size and code complexity.
Older browsers (like IE8 and below) don’t support SVG natively.
What is an API?
An API is a set of rules that allow different software applications to communicate with each other.
Think of it like a bridge that connects two systems and lets them share data or services.

To make this clearer, let's use an example:


•Imagine you're at a restaurant. The waiter (API) takes your order (request), brings it to the chef
(server), and then brings the food back to you (response).

•Similarly, when you search for a course on a website, you send a request through an API, which
then checks the database and sends the result back to you.

APIs are the building blocks for the todays websites in which heavy data is transferred from the
client to server and vice versa.

How Do APIs Work?


APIs work in a simple step-by-step process:
•Request: A client (user) sends a request through the API's URI (Uniform Resource Identifier).

•Processing: The API forwards the request to the server.

•Response: The server processes the request and sends the response back to the API.

•Delivery: The API returns the server's response to the client.


Types of API Architectures:

1.REST (Representational State Transfer) :A simple, flexible API architecture that uses
HTTP methods (GET, POST, PUT, DELETE) for communication.

2.SOAP (Simple Object Access Protocol) :A more rigid protocol that requires XML-based
messaging for communication.

Why Are APIs Important?


•Integration: Connects different software systems (e.g., a payment gateway to an e-commerce
site).
•Automation: Enables automatic data exchange (e.g., weather apps fetching data).
•Scalability: Makes apps modular and easier to maintain.
•Security: Hides internal logic and only exposes endpoints.
Geolocation

A Geolocation API is a type of API that provides access to the geographic location (latitude
and longitude) of a user's device. It allows web or mobile applications to detect where the user is
in the world, either through a browser or mobile hardware.

The HTML Geolocation is used to get the geographical position of a user. Due to privacy
concerns, this position requires user approval. Geo-location in HTML5 is used to share the location
with some websites and be aware of the exact location. It is mainly used for local businesses, and
restaurants, or showing locations on the map. It uses JavaScript to give latitude and longitude to
the backend server.

Most browsers support Geolocation API. Geo-location API uses a global navigator object. In this
article, we will know HTML Geolocation, various properties, methods & their implementation
through examples.
What Can It Do?
With Geolocation APIs, you can:
•Get a user's current location.
•Track real-time movement (e.g., in delivery apps).
•Customize content based on location (e.g., weather, local news).
How It Works
The Geolocation API determines the user’s location using one or more of the following methods:
•GPS (Global Positioning System) – most accurate, used on smartphones.
•Wi-Fi – checks nearby Wi-Fi networks.
•IP Address – approximate location based on IP.
•Cell Towers – mobile data triangulation.

•Geolocation API Syntax


•navigator.geolocation.getCurrentPosition(successCallback, errorCallback, options);
•Part Type Description
•navigator.geolocation Object Built-in object that accesses the user's location
services
•.getCurrentPosition() Method Requests the current location of the device once
•successCallback Function Called when the location is
successfully retrieved
•errorCallback Function (Optional) Called if there is an error getting the location
HTML Structure

<!DOCTYPE html>
<html>
<head>
<title>Geolocation Example</title>
</head>
<body>
<h2>Find My Location</h2>
<button onclick="getLocation()">Get Location</button>
<p id="locationResult"></p>

 !DOCTYPE html>: Declares the document type and version of HTML.


 <title>: Sets the title that appears in the browser tab.
 <h2>: A heading for the page.
 <button>: A button that triggers the getLocation() function when clicked.
 <p id="locationResult">: A paragraph element where the result (latitude and longitude or error
message) will be displayed.
JavaScript Code

function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, showError);
} else {
document.getElementById("locationResult").innerText = "Geolocation is not supported by this
browser.";
}
}

 navigator.geolocation: A Web API that allows web pages to access the geographical location of a
device.
 getCurrentPosition(success, error): Tries to get the current position. If successful, it calls
showPosition; if there’s an error, it calls showError.
Success Callback: showPosition

function showPosition(position) {
const latitude = position.coords.latitude;
const longitude = position.coords.longitude;
document.getElementById("locationResult").innerText =
"Latitude: " + latitude + "\nLongitude: " + longitude;
}

 This function is called if the location is successfully retrieved.


 position.coords.latitude and position.coords.longitude: Contain the GPS coordinates.
 These values are then displayed in the <p> element.
Error Callback: showError  This function is called if there’s a
function showError(error) { problem getting the location.
let message = "";
switch(error.code) {  It uses a switch statement to check
case error.PERMISSION_DENIED: the error.code and set an
message = "User denied the request for Geolocation."; appropriate message:
break;
case error.POSITION_UNAVAILABLE:  PERMISSION_DENIED: User blocked
message = "Location information is unavailable."; the location request.
break;
case error.TIMEOUT:  POSITION_UNAVAILABLE: Location
message = "The request to get user location timed out."; couldn't be determined.
break;
case error.UNKNOWN_ERROR:  TIMEOUT: Took too long to respond.
message = "An unknown error occurred.";
break;  UNKNOWN_ERROR: Something else
} went wrong.
document.getElementById("locationResult").innerText = message;
}
Web Storage API in HTML5 provides a way to store data locally within the user's browser. It is
part of the HTML5 specification and allows websites and web applications to store data persistently
(across sessions) or temporarily (per session), without using cookies.

Types of Web Storage


 Local Storage (localStorage)
• Stores data with no expiration time
• Data is saved across browser sessions
• Accessible only from the same origin (domain + protocol + port)

 Session Storage (sessionStorage)


• Stores data for one session
• Data is lost when the browser tab is closed
• Also accessible only from the same origin
Web Storage API Interfaces
•Storage: It provides access to a particular local storage.

•Window: It is a window containing a DOM document.

•StorageEvent: It is implemented by a storage event which is sent to a window when a storage


area changes.

 Main Attributes and Methods of Web Storage API

•Feature/Attribute Description

•length Returns the number of items stored in the storage object.

•key(index) Returns the key name at the given index in the storage.

•getItem(key) Returns the value associated with the key, or null if the key does
not exist.

•setItem(key, value) Stores a key/value pair. Both key and value are stored as strings.

•removeItem(key) Removes the item associated with the specified key.


Web Storage API Syntax

 Store data
localStorage.setItem("key", "value");
sessionStorage.setItem("key", "value");

storageObject: This is either localStorage or sessionStorage.


key: A string that acts as the identifier for the data.
value: The data you want to store — it must be a string.

 Retrieve data
let value = localStorage.getItem("key");
let value = sessionStorage.getItem("key");

storageObject: This is either localStorage or sessionStorage.


key: The string key for the data you want to retrieve.
value: The returned value (always a string), or null if the key does not exist.
 Remove a specific item
localStorage.removeItem("key");
sessionStorage.removeItem("key");

 Clear all stored data


localStorage.clear();
sessionStorage.clear();
!DOCTYPE html>
<html>
<head>
<title>Web Storage API Example</title>
</head>
<body>

<h2>Welcome to Web Storage Demo</h2>

<input type="text" id="nameInput" placeholder="Enter your name">


<button onclick="saveName()">Save Name</button>
<button onclick="showName()">Show Saved Name</button>
<button onclick="clearName()">Clear Saved Name</button>

<p id="output"></p>
<script>
// Save the name to localStorage
function saveName() {
let name = document.getElementById('nameInput').value;
if(name) {
localStorage.setItem('username', name);
alert('Name saved!');
} else {
alert('Please enter a name.');
}
}

// Retrieve and show the saved name


function showName() {
let savedName = localStorage.getItem('username');
let output = document.getElementById('output');
if(savedName) {
output.textContent = 'Saved Name: ' + savedName;
} else {
output.textContent = 'No name saved yet.';
}
}
// Clear the saved name
function clearName() {
localStorage.removeItem('username');
document.getElementById('output').textContent = 'Saved name cleared.';
}
</script>

</body>
</html>
The Web Workers API is a feature in modern web browsers that allows you to run JavaScript
code in the background, on a separate thread from the main browser thread. This is especially useful
for performing expensive or long-running tasks (like data processing or network requests) without
freezing or slowing down the user interface.

Why Web Workers?


JavaScript runs on a single thread by default, meaning heavy tasks can block the main thread and
cause UI lag or freezing. Web Workers solve this by running scripts in parallel.

How It Works
You create a separate JavaScript file for the worker.
The main script (UI thread) spawns the worker.
The main thread and worker communicate using messages (via postMessage() and onmessage
events)

 Dedicated Web Workers


• Purpose: Designed for a single main script (one-to-one communication).
• Scope: Only accessible by the script that created them.
• Use Case: Offloading tasks like data processing, large calculations, or file parsing.
• Communication: Through postMessage() and onmessage.
Syntax
// main.js
const worker = new Worker("worker.js");
worker.postMessage("Hello");
worker.onmessage = (e) => console.log(e.data)
;

• Worker.js" is the JavaScript file that will run in the background thread.
• The postMessage() function is how you communicate with the worker.
• When the worker sends something back using postMessage(), it will trigger this function.

 Shared Web Workers


• Purpose: Can be accessed by multiple scripts, even across different browser windows, tabs, or
iframes, as long as they are from the same origin.
• Scope: Shared among multiple contexts.
• Use Case: Applications that need inter-tab communication or coordination.
• Communication: Via port objects.
Syntax
// main.js
const worker = new SharedWorker("shared-worker.js");
worker.port.start();
worker.port.postMessage("Hello");
worker.port.onmessage = (e) => console.log(e.data);

• Creates a new SharedWorker from the file shared-worker.js.


• Starts the communication port between the main script and the shared worker.
• Sends a message to the shared-worker.js.
• Listens for messages returned from the shared worker.
• e.data holds the response data sent by the worker.

Service Workers
Purpose: Act as a proxy between the web app and the network; intercept network requests and
cache responses.
Scope: Independent of any particular webpage or tab.
Use Case: Offline support, caching, background sync, push notifications.
Lifecycle: install → activate → fetch
AppCache (Application Cache) is an HTML5 feature that allows a web app to specify
resources (files) that the browser should cache(Cache is a storage layer that saves copies of data or
files temporarily so they can be accessed faster the next time they are needed.) and make available
for offline use. When a user visits the web app, the browser downloads and stores the specified files
locally, so the app can load and run even when the user is offline or the network is slow/unavailable.

 Why Offline Support?


•User Experience: Users can continue to access the app even without an internet connection.
•Performance: Cached resources load faster since they come from the local disk, not the network.
•Reliability: Prevents app breakage due to network failures.

 The Manifest File


The core of AppCache is a manifest file — a simple text file that lists files to be cached. It controls
what the browser stores and serves offline.

 Browser Support and Deprecation


•AppCache was supported in major browsers (Chrome, Firefox, Safari, IE).
•However, AppCache is now deprecated and considered obsolete.
•Modern browsers recommend using Service Workers for offline support due to their greater
flexibility and control.
 Limitations and Issues with AppCache
•Difficult to manage: Cache update rules are rigid and can cause unexpected caching behavior.
•No fine control: Caching applies globally; hard to control cache per resource or use dynamic
caching.
•Complex fallbacks: Limited fallback capabilities, only URL prefix-based.
•Debugging is tricky: Errors related to cache updates are not always clear.
•Security risks: Serving stale cached content if not managed properly.

Feature AppCache VS Service


AppCache Workers
Service Workers
Control over cache Limited (manifest file only) Full control via JavaScript
Advanced (background sync,
Offline capabilities Basic
push)
Programmatic, fine-grained
Cache updates Based on manifest changes
control
Limited (fallback section Customizable with
Fallback handling
only) JavaScript
Debugging Difficult Easier with DevTools
Deprecated, not Current standard for offline
Status
recommended support

You might also like