DEV Community

Valentin Degenne
Valentin Degenne

Posted on

Few things about page loading and styling.

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);
Enter fullscreen mode Exit fullscreen mode

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';
Enter fullscreen mode Exit fullscreen mode

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" />
Enter fullscreen mode Exit fullscreen mode

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay