Module 2 : Installing Bootstrap via CDN.
Use Bootstrap's versioned files from a reputable CDN (jsDelivr or cdnjs) and include Subresource Integrity (integrity) + crossorigin="anonymous". For most projects include the CSS in the <head> and the bootstrap.bundle JS at the end of <body> (the bundle contains Popper and the Bootstrap JS plugins). Example code below is for Bootstrap v5.3.8 (current stable at time of writing).
1. What is a CDN and why use it?
CDN = Content Delivery Network. It’s a global network of cached edge servers that serve static assets (CSS, JS, fonts, images) from a location
geographically near the user. Benefits:
![]() |
Faster initial download for many users (edge caching).
Higher probability the asset is already cached in the user’s browser from another site.
Offloads bandwidth from your server / simpler deployment (no build step required to get started).
Tradeoffs / caveats:
External dependency — if CDN is blocked/fails, your UI can break unless you provide fallback.
Security: third-party assets can be tampered with — mitigate with SRI (Subresource Integrity) and crossorigin.
Version pinning is important — using an exact version avoids surprise breaking changes.
Official Bootstrap docs recommend jsDelivr CDN links and note to use integrity + crossorigin.
2. working example (production-ready) — Bootstrap v5.3.8
The integrity values are taken from the official docs for v5.3.8 — keep them in sync if you upgrade.
getbootstrap.com
<!doctype html> <html lang="en"> <head> <meta charset="utf-8" /> <!-- IMPORTANT: responsive behavior --> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>Bootstrap CDN Example — v5.3.8</title> <!-- Bootstrap CSS (jsDelivr CDN) + Subresource Integrity (SRI) --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-sRIl4kxILFvY47J16cr9ZwB07vP4J8+LH7qKQnuqkuIAvNWLzeN8tE5YBujZqJLB" crossorigin="anonymous" /> <!-- Optional: your own stylesheet that overrides Bootstrap variables/custom rules --> <link rel="stylesheet" href="/css/main.css" /> </head> <body> <main class="container py-5"> <h1 class="mb-4">Bootstrap CDN — Demo</h1> <!-- Example: responsive grid --> <div class="row"> <div class="col-md-6">Left column</div> <div class="col-md-6">Right column</div> </div> <!-- Example: modal trigger --> <button class="btn btn-primary mt-4" data-bs-toggle="modal" data-bs-target="#demoModal"> Open demo modal </button> <!-- Modal --> <div class="modal fade" id="demoModal" tabindex="-1" aria-labelledby="demoModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="demoModalLabel">Modal title</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> Hello — Bootstrap JS (bundle) makes this modal work. </div> </div> </div> </div> </main> <!-- Bootstrap JS bundle (includes Popper) — place at end of body --> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/js/bootstrap.bundle.min.js" integrity="sha384-FKyoEForCGlyvwx9Hj09JcYn3nv7wiPVlz7YYwJrWVcXK/BmnVDxM+D2scQbITxI" crossorigin="anonymous"></script> <!-- Optional: local fallback for JS (see section below) --> </body> </html>
Why this order & attributes?
<meta name="viewport"> — required for Bootstrap’s grid/responsive features to behave correctly on mobile.
getbootstrap.com
CSS in <head> so the page renders styled before paint (prevents flash of unstyled content).
integrity + crossorigin="anonymous" — ensures the file you requested is exactly the file you expect (browser rejects it if the hash doesn't match). See SRI section & MDN for details.
MDN Web Docs
bootstrap.bundle.min.js includes Popper (used by dropdowns/tooltips). Using the bundle avoids separate Popper script ordering issues.
getbootstrap.com
3. Subresource Integrity (SRI)
What SRI does: the browser computes the cryptographic hash of the fetched file and compares it to the integrity value. If they differ, the resource won't be used — this helps protect against CDN compromise or accidental file changes.
How to generate an SRI hash for a file (CLI) — example using openssl (Linux/macOS):
# compute sha384 base64 for a remote file (example for CSS) curl -sS https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css \ | openssl dgst -sha384 -binary | openssl base64 -A # result: (base64 text) -> use as: integrity="sha384-<base64>"
Or use online tools such as SRIHash.org (handy for quick checks).
srihash.org
+1
Important: update the SRI value each time you upgrade to a different version/file.
4. Fallback strategies (if CDN fails)
Why: CDNs are reliable but can be blocked or temporarily down. Add a local fallback so your users still see styles or have JS functionality.
CSS fallback (simple onerror):
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css" onerror="this.onerror=null;this.href='/css/bootstrap-local.min.css'">
This replaces the href with your local copy if the CDN stylesheet errors. (Technique recommended in many community posts and docs.)
Stack Overflow
JS fallback (check library exposure):
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/js/bootstrap.bundle.min.js" integrity="sha384-FKyoEForCGlyv..." crossorigin="anonymous"></script> <script> // If bootstrap didn't load, load local copy if (typeof bootstrap === 'undefined') { const s = document.createElement('script'); s.src = '/js/bootstrap.bundle.min.js'; document.head.appendChild(s); } </script>
This checks for the bootstrap global and injects a local script if absent. (Common fallback pattern.)
hanselman.com
5. ESM
Bootstrap provides ESM builds (bootstrap.esm.min.js) so you can import components — useful for SPA setups or selective imports. If you use the ESM files you must handle the Popper dependency or use import maps. See Bootstrap’s JS docs for examples.
getbootstrap.com
6. Exercises
Exercise 1 Add Bootstrap via CDN & create a responsive header
Create index.html with the CDN CSS from the example and add a .navbar with brand and two links.
Hint: Use <nav class="navbar navbar-expand-md navbar-light bg-light"> and place the collapsible list inside .collapse.navbar-collapse.
Expected outcome: Navbar collapses to a hamburger on small screens and expands on larger screens.
Exercise 2 Grid
Create a three-column responsive layout that becomes one column on sm devices and two columns on medium screens.
Hint: Use col-12 col-md-6 col-lg-4 on column <div>s.
Expected outcome: On small phones columns stack; on tablets two columns; on desktop three columns.
Exercise 3 Modal & JS components
Using the CDN JS bundle, create a button that opens a modal whose body contains a form (name + email). Validate with HTML5 required.
Hint: Use data-bs-toggle="modal" and data-bs-target="#myModal".
Expected outcome: Clicking button opens modal, form prevents submit if required fields empty.
Exercise 4 SRI tamper test
Load the CDN link with correct SRI, then change the SRI string to a wrong value and observe.
Expected: Browser refuses to load the resource (CSS won't apply or JS won't execute). Record the console/network behavior (error messages).
Purpose: Demonstrates SRI effectiveness.
Exercise 5 — Fallback test
Implement the CSS onerror fallback + JS global check fallback. Simulate CDN failure by pointing the CDN URL to a non-existent file (or by blocking that URL in devtools).
Expected: Local fallback loads and the site still functions (may look different if your local file differs).
Exercise 6 — Advanced: Minimal Bootstrap build
Use npm to install Bootstrap locally, compile a custom build with only the components you need using Sass and the Bootstrap source (e.g., only grid + buttons). Compare minified sizes vs the CDN full bundle.
Commands (starter):
npm init -y npm i bootstrap@5.3.8 sass # Import only what you need in a custom scss and compile with sass
Expected: A smaller CSS file tailored to your app.
7. Measure CDN vs local performance and reliability
Goal: Compare perceived & performance when Bootstrap is served from CDN vs locally hosted.
Setup
Two simple pages: cdn.html (uses jsDelivr CDN) and local.html (uses local bootstrap.min.css + bootstrap.bundle.min.js).
Host both on same local dev server (so server speed is constant).
Steps
Open Chrome DevTools → Network → throttle the network to Fast 3G (or select “Offline” for failure tests).
Load cdn.html. Record:
Time to First Contentful Paint (FCP)
Total bytes transferred
Number of requests
Was the CSS/JS served from the CDN (look at response headers & remote host)
Clear cache, load local.html and record the same metrics.
Repeat after loading cached CDN file (simulate a user who already visited another site using that CDN file). Then reload cdn.html and measure cached load vs local cached load.
Test CDN failure: block the CDN host in DevTools or set the CDN URL to a 404. Verify fallback behavior (onerror or JS fallback). Record failures & measure time to recovery (how long until fallback file fetched).
What to collect
Lighthouse audit (Performance & Best Practices) for both pages.
Network waterfall screenshots.
Console messages for SRI mismatch (if tampered).
Expected findings
Cold cache: CDN may be slightly faster (edge server + HTTP/2 benefits).
Cached CDN assets: huge win — near instant (if user already visited a site using same CDN + version).
Local hosting: may be preferable in intra-network (intranets), or when strict CSP/SRI policies disallow remote resources.
SRI protects integrity but means you must update integrity when upgrading.
8. Research
valuable directions and references:
Subresource Integrity & best — MDN article and implementation notes.
Bootstrap ESM and selective imports — Bootstraps’s JS docs for ESM usage (import maps, Popper dependency). Good for modern app architectures.
CDN comparison & reliability — compare jsDelivr, cdnjs, unpkg: cost, cache footprint, geographic coverage. (jsDelivr is recommended on Bootstrap docs.)
Suggested research projects:
Measure SRI adoption on the top 10,000 sites — how many use integrity + do they pin versions?
Compare typical TTLs for different CDNs and how frequently files change (tradeoff: long TTLs vs update agility).
Evaluate privacy/telemetry implications — loading external CDNs leaks referrer/visitor IP to the CDN provider.
9. (concise)
Pin versions (e.g., @5.3.8) so you control upgrades. Do not rely on unpinned “latest” in production.
getbootstrap.com
Use SRI for CDN assets and test SRI on each deploy.
Use the bundle (bootstrap.bundle.min.js) for simplicity (includes Popper). For advanced builds using a bundler, use ESM/ES build and import only needed components.
For maximum reliability, use CDN + local fallback or host assets behind your own CDN/edge when you need strict control.
10. checklist
Add <meta name="viewport" content="width=device-width, initial-scale=1">
Add Bootstrap CSS link with integrity + crossorigin
Add bootstrap.bundle.min.js before </body> with integrity + crossorigin
Provide fallback for CSS & JS (optional but recommended for production)
Run Lighthouse & a11y checks (contrast, keyboard navigation) on your pages
Pin versions and update SRI when upgrading.






No comments:
Post a Comment