Few things about page loading and styling.
Valentin Degenne
Posted on December 28, 2023
One thing to keep in mind when designing a website is that the browser can fetch several resources when the page loads but has a limitation on how many it can download at a time.
So one must be wise and put all the necessary things at the beginning: code splitting can help with that.
But it's a double edged sword problem, split enough to make things load in parallel and speed up the lcp but do not split too much because it could defer the loading of some needed scripts.
StyleSheets
Applying a style from a script...
One solution to reduce the number of requests sent to your server is to slide your stylesheets directly inside your scripts.
import neededStyles from './need-styles.css' with {type: 'css'};
document.adoptedStyleSheets.push(neededStyles);
A document or shadow root can have as many stylesheets as supported and stylesheets stack on top of each other (assuming push
is being used). Adding a new stylesheet doesn't discard the previously added ones but will replace the css properties in common.
modulepreload
- Fetch scripts before they are even requested in others, that can speed up the load time (compared to requesting them in cascade over the network at execution time).
- However preloading a module doesn't execute the script*!* (it just preloads its content).
- Preloading a module won't cause a preloading cascade, every scripts need to explicitely be preloaded even the ones included inside a preloaded script:
main.js
:
import './sub.js';
index.html
:
<link rel="modulepreload" href="./main.js" />
<!-- The following preload is also needed
even though `sub.js` is imported from `main.js` -->
<link rel="modulepreload" href="./sub.js" />
Posted on December 28, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 30, 2024