Skip to content
Tutorials Center
My learning

Topics

Lesson 47 of 58 ยท Quality

Performance and Best Practices

Make Bootstrap pages fast and maintainable: know the file sizes, choose CDN or self-hosting, add SRI, avoid override fights, trim unused CSS and plan a v4 upgrade.

Bootstrap is a big toolbox, and a page rarely needs the whole toolbox. This lesson is about the choices that decide whether a Bootstrap site feels fast and stays easy to change: how much you download, where you load it from, how you protect it, how you write your own CSS next to it, and how to remove what you do not use. It ends with the main points to remember when you upgrade an old Bootstrap 4 project.

How big is Bootstrap?

Knowing the numbers helps you judge every other decision. These are the Bootstrap 5.3.3 distribution files, measured from the jsDelivr CDN (gzip level 9; real servers may use the smaller Brotli format):

File Uncompressed Gzipped
css/bootstrap.min.css about 233 KB about 31 KB
js/bootstrap.bundle.min.js (all plugins + Popper) about 81 KB about 24 KB
js/bootstrap.min.js (plugins only, needs Popper for some) about 61 KB about 16 KB

On a modern connection, 31 KB of CSS is small. It still matters because CSS blocks rendering: the browser will not paint the page until the stylesheet has arrived. And the bytes compound with fonts, images and your own code. The fastest request is the one you never make, so trim before you optimize.

A few quick wins, no build tools needed:

  • Load the JavaScript only if the page uses a component that needs it (modal, dropdown, collapse, tooltip, carousel, toast, offcanvas). Static pages with grid, cards and utilities need no Bootstrap JavaScript at all.
  • Put the script at the end of <body> or add defer, so it never delays the first paint.
  • Use bootstrap.min.js plus Popper only if you need dropdowns, tooltips or popovers; if you use none of them, bootstrap.min.js alone is enough. The bundle is the convenient choice when in doubt.
  • Do not load Bootstrap twice (for example a theme that bundles it plus your own link), and do not @import it inside another CSS file, which creates a slower request chain. Use <link> tags.
  • Give images width and height (or a .ratio wrapper) and loading="lazy" below the fold, so layout does not jump while they load.

CDN or self-hosting?

A CDN (content delivery network) serves Bootstrap from shared servers. Self-hosting means copying the files to your own server (or your own CDN) and linking them from your domain.

The old argument for a public CDN was "visitors already have it cached from another site". That no longer works: modern browsers partition their cache per site, so a file cached for one website is not reused by another. Today the trade-offs are different:

Public CDN Self-hosted
Setup One <link> tag Copy files, deploy them
Connection Extra DNS lookup and TLS handshake to another host Same connection as your HTML (HTTP/2 or HTTP/3 multiplexing)
Availability Depends on a third party Under your control
Privacy The CDN sees your visitors' requests No third party
Customization Stock files only Your own Sass build, subset, versioned names
Caching Long cache headers already set You set them (see below)

Rule of thumb: the CDN is excellent for tutorials, prototypes, demos and the live examples on this site. For a production site, self-host (ideally your own compiled, trimmed file) and serve it with a far-future cache header on a versioned filename:

TEXT
Cache-Control: public, max-age=31536000, immutable

When the file changes you change its name (site.4f2a9c.css), so browsers fetch the new one and never serve a stale one.

flowchart TD
  S{"What are you building?"} -->|"Prototype, demo, tutorial"| CDN["Use the CDN link<br/>pin the version"]
  S -->|"Production site"| H{"Own Sass build?"}
  H -->|yes| SELF["Self-host the compiled file<br/>versioned name + long cache"]
  H -->|no| SELF2["Self-host the dist files<br/>or CDN with SRI"]

Pin the version either way; the choice is about control, not about speed alone.

If you do use a CDN, warm up the connection early by placing this before the stylesheet:

HTML
<link rel="preconnect" href="https://cdn.jsdelivr.net" crossorigin>

Subresource Integrity (SRI)

When you load a script from someone else's server, you trust it completely: if the CDN were compromised, the attacker's code would run on your page. Subresource Integrity removes that trust. You add a hash of the exact file you tested. The browser downloads the file, hashes it and refuses to use it if the hash is different.

You need two attributes: integrity and crossorigin="anonymous" (the CDN sends the CORS headers SRI requires). These are the real hashes for the 5.3.3 files:

Loading Bootstrap with SRI

You can compute the hash of any file yourself. With OpenSSL installed:

Terminal
curl -s https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css \
  | openssl dgst -sha384 -binary | openssl base64 -A

Prefix the result with sha384-. SRI only works with a pinned, exact version. A floating URL such as bootstrap@5 would change under you and fail the check, which is another reason to always pin.

Write CSS that does not fight Bootstrap

Most "Bootstrap is hard to override" stories come from specificity. Remember how the browser decides between two rules: the one with the more specific selector wins, and with equal specificity the later one wins. Inline styles and !important sit above that. Bootstrap's own utilities carry !important, which is why a class like text-center always works.

Trouble starts when you answer a Bootstrap rule with a stronger selector, then need a still stronger one for the next case, and soon every rule has !important or an ID selector.

Here is a typical trap. A navbar link color is changed with a selector:

Fighting the selector versus changing the variable

In A, the .fight .nav-link rule has the same specificity as Bootstrap's :hover rule and appears later, so hover no longer changes the color. The active link, matched by the stronger .navbar-nav .nav-link.active, ignores your rule completely and keeps Bootstrap's color. In B the component's own rules do the work and every state stays consistent.

Habits that keep your CSS and Bootstrap on good terms:

  1. Change variables first, as you learned in Customizing with CSS Variables.
  2. Use utilities for one-off changes (mt-4, text-end) instead of new rules.
  3. Load your stylesheet after Bootstrap so equal-specificity rules resolve in your favor, with no need for stronger selectors.
  4. Keep selectors flat. One class (.hb-callout) beats .container .row .col div.card > .card-body p. Avoid ID selectors for styling and avoid !important in components.
  5. Never edit Bootstrap's files (in node_modules or the dist folder). Your changes vanish at the next install and make upgrades painful.
  6. Prefix your own classes (hb-) so they never collide with a future Bootstrap class.
  7. Avoid inline style attributes for anything except custom properties.

Removing CSS you do not use

A typical page uses a small fraction of Bootstrap's selectors. You can measure this in the browser. The script below walks the stylesheet, counts the style rules, and asks the page which of them match anything. It needs the stylesheet to be CORS-readable, which is why the <link> has crossorigin="anonymous".

How much of Bootstrap does this page use?

The exact numbers differ a little between browsers, but the message is always the same: most rules match nothing on a simple page. Of course, a whole site uses more than one page, so the real question is what the union of your pages needs. There are three ways to trim.

1. Import only the Sass partials you use (best). Covered in Customizing with Sass. It is the safest method, because you list components by name and the compiler checks the dependencies.

2. Purge unused CSS with a tool. Tools such as PurgeCSS scan your templates for class names and delete rules that never appear. They can shrink the file a lot, but they cannot read your mind: classes that are built in JavaScript ('btn-' + kind) or added by Bootstrap's own scripts (show, collapsing, modal-backdrop, modal-open, offcanvas-backdrop, tooltip, popover, fade) look unused and get deleted, which silently breaks components. A safelist protects them:

JavaScript
// purgecss.config.js (read-only example)
module.exports = {
  content: ['./templates/**/*.html', './src/**/*.js'],
  css: ['./dist/custom.css'],
  safelist: {
    standard: ['show', 'collapse', 'collapsing', 'fade', 'modal-backdrop', 'modal-open',
               'offcanvas-backdrop', 'dropdown-menu', 'tooltip', 'popover', 'was-validated'],
    greedy: [/^bs-/, /^data-bs-/, /^carousel-item/],
  },
};

Always test every interactive component after purging.

3. Do nothing. For a small site, 31 KB compressed is often not worth any build complexity. Measure before you optimize.

Check the basics

A short checklist for any Bootstrap page before it goes live:

  • <!doctype html>, lang, and <meta name="viewport" content="width=device-width, initial-scale=1"> are present.
  • Bootstrap is loaded once, with a pinned version, and SRI if from a CDN.
  • JavaScript is loaded only where needed, at the end of the body or with defer.
  • Images have dimensions and img-fluid; below-the-fold images use loading="lazy".
  • No !important, ID selectors or edits to Bootstrap's files in your CSS.
  • The page works at 320 px wide and at 200% zoom, with no horizontal scroll.
  • Interactive components work with the keyboard (see Accessibility in Bootstrap).

Upgrade notes from Bootstrap 4

Many tutorials and templates still target Bootstrap 4. If you are moving a project to 5, these are the changes you will meet most. The full walkthrough is in the next lesson; this is the short map.

Bootstrap 4 Bootstrap 5
jQuery required No jQuery; plain JavaScript
data-toggle, data-target, data-dismiss data-bs-toggle, data-bs-target, data-bs-dismiss
.ml-*, .mr-*, .pl-*, .pr-* .ms-*, .me-*, .ps-*, .pe-* (start and end, for right-to-left support)
.float-left, .text-left .float-start, .text-start
.form-group, .form-row Spacing utilities such as .mb-3, and .row g-*
.custom-select, .custom-control .form-select, .form-check
.sr-only .visually-hidden
.close .btn-close
.no-gutters .g-0
.btn-block .d-grid on the parent (and gap-*)
.badge-primary .text-bg-primary
.font-weight-bold .fw-bold
.card-deck, .jumbotron, .media Removed: use the grid, utilities and flexbox
Five breakpoints (xl the largest) Six breakpoints: xxl (1400 px) added

Other differences worth knowing: Bootstrap 5 dropped Internet Explorer, Popper is version 2, CSS variables replace many Sass-only customizations, there is dark mode, and the grid gutters are now set with g-* classes.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why is a public CDN no longer a guaranteed speed win for loading Bootstrap?

    Cache partitioning means each site downloads its own copy, so the old shared-cache benefit is gone. Control and extra connections matter more now.
  2. 2. What do you need to add to a CDN link tag to use Subresource Integrity?

    The integrity hash lets the browser verify the file, and crossorigin="anonymous" allows the CORS request SRI requires.
  3. 3. Your .navbar .nav-link { color: red } rule does not change the active link. What is the best fix?

    The active state is matched by a more specific Bootstrap selector. Changing the variables the component reads themes every state without a specificity fight.
  4. 4. What is the main risk of purging unused CSS automatically?

    Purge tools scan for literal class names. Classes such as show, collapsing and modal-backdrop appear at runtime, so they need a safelist.
  5. 5. Which Bootstrap 4 class became .visually-hidden in Bootstrap 5?

    The screen-reader-only helper was renamed to .visually-hidden.

Summary

  • Bootstrap 5.3.3 is about 31 KB of gzipped CSS and 24 KB of gzipped JavaScript (bundle); CSS blocks rendering, so trim and load JavaScript only when needed.
  • Use a CDN for prototypes; self-host with versioned filenames and long cache headers for production.
  • Add integrity and crossorigin="anonymous" to CDN links, and always pin an exact version.
  • Avoid override fights: change variables, use utilities, keep selectors flat, load your CSS last, and never edit Bootstrap's files.
  • Trim CSS by importing only the Sass partials you use; purge tools need a safelist for runtime classes.
  • Bootstrap 4 to 5 mostly renames classes and data attributes and removes jQuery.

Next lesson: Migrating from Bootstrap 4 and Using Icons.