Web Optimization FAQ
Web Optimization FAQ
body {
font-family: Arial, sans-serif;
line-height: 1.6;
}
header {
background: #333;
color: #fff;
padding: 1em;
text-align: center;
}
nav ul {
list-style: none;
padding: 0;
}
nav ul li {
display: inline-block;
margin: 0 0.5em;
}
nav ul li a {
color: #fff;
text-decoration: none;
}
main {
padding: 1em;
}
.content, .sidebar {
margin-bottom: 1em;
}
footer {
background: #333;
color: #fff;
text-align: center;
padding: 1em;
}
Step 3: Add Media Queries for Tablet and Desktop Layouts
@media (min-width: 600px) {
main {
display: flex;
flex-wrap: wrap;
}
.content {
flex: 2;
padding-right: 1em;
}
.sidebar {
flex: 1;
padding-left: 1em;
}
}
.sprite {
width: 100px;
height: 100px;
background-image: url('sprite.png');
background-repeat: no-repeat;
display: inline-block;
}
Style.css
.sprite { background: url('sprite.png') no-repeat top left; width: 150px; height:
104px; }
.sprite.bear { background-position: 0 0; }
.sprite.elephant { background-position: 0 -114px; }
.sprite.tiger { background-position: 0 -228px; }
Report1
Report2
Q11) - How does `requestAnimationFrame` differ from other
JavaScript animation methods? Create a simple animation
using `requestAnimationFrame` and measure its performance
compared to using `setInterval
Ans) requestAnimationFrame is a JavaScript method designed
specifically for animating web content. It is more efficient
than other traditional methods like setInterval or setTimeout
because it synchronizes with the browser's refresh rate. By
leveraging requestAnimationFrame, the browser can optimize
animations to reduce unnecessary frames, minimize battery
usage, and create smoother animations.
Key Differences Between requestAnimationFrame and Other
Animation Methods
1. Synchronization with the Browser’s Refresh Rate:
requestAnimationFrame calls the animation function just
before the next repaint, usually at 60 frames per second
(fps) on most devices. This synchronization reduces visual
stuttering and aligns with the browser’s native redraw
process.
2. Automatic Frame Skipping: If the animation is running in
the background or the user is idle,
requestAnimationFrame will throttle the animation,
saving computational power and battery life. setInterval,
however, will continue executing at the specified interval
regardless of visibility.
3. Optimized for Animation: requestAnimationFrame is
specifically optimized for animations, allowing it to
handle CSS and JavaScript animations with smoother
transitions compared to setInterval.
Code:
4. let canvas = document.getElementById('myCanvas');
5. let context = canvas.getContext('2d');
6. canvas.width = window.innerWidth;
7. canvas.height = window.innerHeight;
8.
9. let ball = {
10. x: 50,
11. y: 50,
12. dx: 2,
13. dy: 4,
14. radius: 20,
15. color: 'blue'
16. };
17.
18. function drawBall() {
19. context.clearRect(0, 0, canvas.width, canvas.height);
20. context.beginPath();
21. context.arc(ball.x, ball.y, ball.radius, 0, Math.PI * 2);
22. context.fillStyle = ball.color;
23. context.fill();
24. context.closePath();
25. }
26.
27. function updateBallPosition() {
28. ball.x += ball.dx;
29. ball.y += ball.dy;
30.
31. if (ball.x + ball.radius > canvas.width || ball.x - ball.radius < 0) {
32. ball.dx *= -1; // Reverse direction
33. }
34.
35. if (ball.y + ball.radius > canvas.height || ball.y - ball.radius < 0)
{
36. ball.dy *= -1; // Reverse direction
37. }
38. }
39.
40. function animate() {
41. drawBall();
42. updateBallPosition();
43. requestAnimationFrame(animate);
44. }
45.
46. // Start the animation loop
47. requestAnimationFrame(animate);
48.
Report1(By using set Interval)
Report2(By using request animation frame)
Q13) - How can you implement asset caching strategies using
Cache-Control headers and service workers? Configure asset
caching for a webpage and measure the load time
improvements.
Ans)Asset caching strategies are essential for optimizing web
page load times, especially for frequently accessed resources
like images, stylesheets, and scripts. By leveraging Cache-
Control headers and service workers, we can store assets in
the browser, reducing the need to fetch them from the server
on every visit, which significantly reduces load times and
bandwidth usage
Understanding Cache-Control Headers
The Cache-Control header is an HTTP header that tells the
browser how to handle caching for a particular asset. Here are
some common directives:
1. public: Allows caching by the browser and any
intermediate caches (like a Content Delivery Network).
2. private: Allows caching only in the browser, preventing
caching by intermediate caches.
3. max-age: Specifies how long (in seconds) the asset should
be considered fresh.
4. no-store: Ensures the resource is never cached and is
always retrieved from the server.
5. no-cache: Allows caching but requires revalidation with
the server before each use.
6. immutable: Used with max-age to specify assets that
never change, reducing the need for revalidation.
Service-worker.js
Code: const CACHE_NAME = 'my-cache-v1';
const ASSETS_TO_CACHE = [
'/',
'/index.html',
'/image.jpg',
'/styles.css',
'/script.js'
];
const MAX_AGE = 2 * 60 * 1000; // 2 minutes in milliseconds
Server.js
const express = require('express');
const app = express();
const path = require('path');
app.use(express.static('public', {
maxAge: '30d',
setHeaders: (res, filePath) => {
if (filePath.endsWith('.html')) {
res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate');
} else {
res.setHeader('Cache-Control', 'public, max-age=2592000');
}
}
}));
Code:
const gulp = require('gulp');
const cssnano = require('gulp-cssnano');
const uglify = require('gulp-uglify');
const concat = require('gulp-concat');
const watch = require('gulp-watch');
gulp.task('minify-css', () => {
return gulp.src('public/css/*.css')
.pipe(concat('styles.min.css'))
.pipe(cssnano())
.pipe(gulp.dest('public/dist/css'));
});
gulp.task('minify-js', () => {
return gulp.src('public/js/*.js')
.pipe(concat('scripts.min.js'))
.pipe(uglify())
.pipe(gulp.dest('public/dist/js'));
});
gulp.task('watch', () => {
gulp.watch('public/css/*.css', gulp.series('minify-css'));
gulp.watch('public/js/*.js', gulp.series('minify-js'));
});
const options = {
root: null,
rootMargin: '0px',
threshold: 0.1
};
images.forEach(image => {
observer.observe(image);
});
</script>
</body>
</html>
Q19) - What is critical CSS, and how can you inline it into an
HTML document? Implement critical CSS on a webpage and
measure the performance improvement using Google
PageSpeed Insights.
Ans)) Critical CSS refers to the essential styles that are required
to render the content of the page above the fold (the visible
area of a webpage before scrolling). It helps prioritize the
loading of CSS that affects the initial viewport, improving the
page’s perceived load speed by ensuring the browser can
render the page as quickly as possible.
By inlining Critical CSS directly into the <head> of an HTML
document, you allow the browser to immediately apply these
styles as the page loads, without needing to wait for the
external CSS file to download. This can result in faster rendering
times and a better user experience, especially for users on
slower networks.
Commond: critical index2.html --inline --css style.css --width
1300 --height 900 > index-critical.html
(It will generate and merge the critical css in the output file)
Q21) Using Chrome DevTools, analyze the number of HTTP
requests made by a webpage. How can you reduce the number
of requests and optimize the loading of assets?
Ans)Reducing the Number of HTTP Requests and Optimizing
Asset Loading
Once you have analyzed the network requests, you can
optimize the page load by reducing the number of HTTP
requests and improving the loading of resources. Below are
several strategies you can implement:
1. Minimize the Number of HTTP Requests:
Combine CSS Files: Instead of having multiple CSS files,
combine them into a single CSS file to reduce the number
of HTTP requests.
Combine JavaScript Files: Similarly, you can combine
multiple JavaScript files into one to reduce the number of
requests.
Use CSS Sprites for Images: If you have many small images
(e.g., icons), combine them into a single image file known
as a CSS sprite. This way, only one HTTP request is made
for all the images, and you use background-position to
display specific parts of the sprite.
Inline Small CSS and JavaScript: Inline critical CSS and
JavaScript directly into the HTML document. This
eliminates the need for separate requests for those small
resources, improving load speed. For example, the critical
CSS for rendering above-the-fold content can be inlined
into the HTML <head>.
Use Data URIs: Small images (such as icons) can be
embedded directly into the HTML or CSS files using data
URIs, eliminating the need for separate HTTP requests for
these resources.
2. Optimize Asset Loading:
Lazy Load Images and Videos: Implement lazy loading for
images, videos, and other non-critical resources. This
technique defers the loading of images and videos that are
outside the viewport, loading them only when the user
scrolls down to them. In HTML, you can use the
loading="lazy" attribute for images.
html
Copy code
<img src="image.jpg" alt="Description" loading="lazy">
Defer or Async JavaScript: Use the defer or async
attributes for JavaScript files to prevent blocking the
rendering of the page. The defer attribute ensures that the
script is executed after the HTML is fully parsed, while
async loads the script in parallel with the page load.
html
Copy code
<script src="script.js" defer></script>
Use HTTP/2: HTTP/2 is a major revision of the HTTP
protocol that improves the performance of asset loading
by allowing multiplexing (sending multiple requests in
parallel over a single TCP connection), reducing the
overhead caused by multiple HTTP requests.
Minify CSS, JavaScript, and HTML Files: Minification
removes unnecessary characters (such as whitespace and
comments) from CSS, JavaScript, and HTML files, reducing
their size and, consequently, the number of bytes
transferred over the network. Tools like UglifyJS for
JavaScript and CSSNano for CSS can help with this.
Use Gzip or Brotli Compression: Enable Gzip or Brotli
compression on your server for text-based resources (e.g.,
CSS, JavaScript, HTML). This reduces the size of the
transferred data, leading to faster load times.
3. Use Content Delivery Networks (CDNs):
Host Static Assets on CDNs: Offload static assets (e.g.,
images, CSS, JavaScript) to a Content Delivery Network
(CDN). CDNs distribute your resources across multiple
geographically dispersed servers, ensuring that users
download assets from the server closest to them, reducing
latency and improving load times.
Use Third-Party CDNs for Libraries: For common libraries
such as jQuery, Bootstrap, or FontAwesome, use a CDN
instead of hosting them yourself. This reduces the number
of requests made to your server and may even speed up
loading if the user has already cached the library from a
previous visit to another site.
4. Prioritize Critical Resources:
Critical CSS: Inline the critical CSS needed to render above-
the-fold content into the HTML to ensure that it loads
quickly. You can then defer the loading of the rest of the
CSS using the media="print" method or load it
asynchronously.
html
Copy code
<link rel="stylesheet" href="critical.css">
<link rel="stylesheet" href="styles.css" media="print"
onload="this.media='all'">
Preload Important Resources: Use the <link
rel="preload"> tag to instruct the browser to load key
resources (such as fonts, stylesheets, or scripts) as early as
possible, improving page load performance.
html
Copy code
<link rel="preload" href="important.js" as="script">
5. Remove Unused CSS and JavaScript:
PurgeCSS: Remove unused CSS using tools like PurgeCSS.
This tool scans your HTML, JavaScript, and other files to
detect which CSS rules are actually used on your page, and
eliminates the unused ones, resulting in smaller CSS files.
UnCSS: Similar to PurgeCSS, UnCSS removes unused CSS
from your stylesheets by analyzing the content of your
HTML.
Q23) How do prefetching and preloading differ in terms of
optimizing asset loading? Implement both techniques on a
webpage and measure the performance improvements.
Ans) Prefetching and preloading are techniques used to
optimize the loading of assets (such as images, scripts, and
stylesheets) on webpages. Both are designed to improve page
load times by reducing latency and ensuring that critical
resources are available when needed, but they function
differently.
Understanding their differences is crucial in making the right
decisions for optimizing performance.
1. Prefetching:
Definition: Prefetching refers to the process of downloading
resources that might be needed in the near future, such as
resources for a subsequent page or for an action the user might
take soon. It’s a proactive approach to fetching resources
ahead of time.
How it Works:
When a browser prefetches a resource, it downloads the
file in the background while the user is currently engaged
with the page. The idea is to anticipate what the user will
need next (such as on a next page or after a particular
action) and load it ahead of time.
Prefetched resources are stored in the browser cache but
are only used when needed (e.g., when navigating to the
next page or opening a new section). The browser doesn't
block rendering or wait for these prefetched resources to
load before displaying the current page.
Use Case: Prefetching is useful when you know the user is likely
to navigate to another page or trigger an action. For example, a
link to a next article or a page within a multi-step form.
HTML Syntax for Prefetching:
html
Copy code
<link rel="prefetch" href="next-page.css" as="style">
<link rel="prefetch" href="next-page.js" as="script">
rel="prefetch" indicates that the browser should prefetch
the resources.
The href attribute points to the resource URL.
The as attribute indicates the type of resource being
fetched (e.g., script, style, image).
2. Preloading:
Definition: Preloading is the process of explicitly loading
resources that are required to render the current page. It’s a
technique used to load critical resources (such as fonts, CSS,
and JavaScript) as early as possible, so they are available
immediately when needed.
How it Works:
When you preload a resource, the browser will fetch it
immediately and make it available for use as soon as it's
needed, without waiting for the page to finish rendering.
Preloading is typically used for resources that are
necessary for the immediate display or functionality of the
page. Unlike prefetching, which targets future needs,
preloading is focused on the current page's requirements.
Use Case: Preloading is essential for critical resources (e.g.,
stylesheets and JavaScript files) that must be loaded before
rendering the content. For example, fonts used in the main
layout of the page or JavaScript for interactivity.
HTML Syntax for Preloading:
html
Copy code
<link rel="preload" href="main.css" as="style">
<link rel="preload" href="app.js" as="script">
<link rel="preload" href="font.woff2" as="font"
type="font/woff2" crossorigin="anonymous">
rel="preload" tells the browser to load the resource.
The href specifies the URL of the resource.
The as attribute defines the type of resource (e.g., script,
style, font).
The type and crossorigin attributes are useful for
preloading fonts.
Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Prefetching and Preloading Images Example</title>
<script src="script.js"></script>
</body>
</html>