Import necessary styles into the shadow DOM

Embracing the concept of shadow dom styles encapsulation is exciting, but I wish to incorporate base styles into each shadow dom as well (reset, typography, etc).

 <head>
 <link rel="stylesheet" href="core.css">
 ...
 </head>

 <my-component></my-component>
 <script>
   
   customElements.define('my-component', class MyComponent extends HTMLElement {
     ...
     connectedCallback() {
        this.shadow = this.attachShadow({mode: 'open'});
         const linkElem = document.createElement('link');
         linkElem.setAttribute('rel', 'stylesheet');
         linkElem.setAttribute('href', 'core.css');

         // applying existing "core.css" to current shadow dom 
         this.shadow.appendChild(linkElem);
     }
   });
 </script>

With core.css being called (linked) twice, could there be an impact on performance?

Answer №1

If you're looking to optimize your styling approach, consider using Constructable Stylesheet Objects. By defining global styles and then incorporating them with shadowRoot.adoptedStylesheets, you can enhance the efficiency of your components:

import {
    resetSheet,
    headlinesSheet,
    coreSheet,
} from '/style-system.js';
import {
    myComponentStyles,
} from './styles.js';

// ...

connectedCallback() {
    // Only compose styles once
    if (!this.shadowRoot.adoptedStyleSheets.length) {
        this.shadowRoot.adoptedStyleSheet = [
            // global stylesheets
            resetSheet,
            headlinesSheet,
            coreSheet,
            // specific sheet for this component
            myComponentStyles
        ]
    }
}

By utilizing this method, you gain several advantages over manually linking style elements to each component:

  • You can share global styles across multiple components by defining them once
  • The component only loads the necessary styles when rendered, improving performance through lazy loading
  • You can dynamically modify global styles (as they are JavaScript components), simplifying updates without affecting multiple elements

To deepen your understanding of Constructable Stylesheet Objects, consider exploring the following resources:

  1. Constructible Stylesheets
  2. Why Would Anyone Use Constructible Stylesheets, Anyways?
  3. Adopt a Design System inside your Web Components with Constructable Stylesheets

Answer №2

When the browser caches the request for core.css, there is no real performance penalty. However, because the stylesheet will be loaded asynchronously, you may experience a flash of unstyled content (FOUC) as the browser retrieves the css for the first time.

To potentially avoid this issue, one solution is to preload the css file in your document within the <head> section. This way, it should (although preloads are merely 'hints' to the browser) be accessible by the time your Shadow DOM is parsed:

<link rel="preload" href="core.css" as="style">

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

JavaScript - Utilizing jQuery to dynamically add and remove input fields

I have a form where input fields (groups) are added dynamically. Here's a glimpse of the complex form: FIDDLE The error on the console reads: Error: uncaught exception: query function not defined for Select2 s2id_autogen1 With existing fields in t ...

The passport authentication process is currently stalled and failing to provide any results

The current authentication process is functioning properly app.post('/login', passport.authenticate('local-login', { successRedirect: '/home', failureRedirect: '/login', failureFlash: true }) ); Howev ...

Error encountered while validating jQuery word cloud

Can anyone please assist me with validating a jQuery word cloud in HTML5? I'm encountering issues with all of the rel values showing this error message: "Bad value 1 for attribute rel on element a: Not an absolute IRI. The string 1 is not a registere ...

Tips on converting comma-separated values into HTML table rows using <tr> tags

JSON Data { "catalog_name": ["Sistem Autodownline ", "Karipap Pusing Ayu"], "price": ["100", "8"], "qty": "", "qty2": ["", ""], "total_qty": "", "total": "", "mem": "10", "email_2": "", "ic_add": "890527-08-6136", "c ...

Is it time to refresh the sibling element when it's selected, or is there

I have recently started working with react and TypeScript, and I am facing some challenges. My current task involves modifying the functionality to display subscriptions and transactions on separate pages instead of together on the same page. I want to sh ...

Using Vue.js to process JSON data

My issue lies within this JSON data. I am trying to consume only the first element of the array using Vue.js 2 in order to display it. I was able to achieve this successfully using the console, but not with Vue.js. This line of code in the console works: ...

Tips for incorporating a return statement within a network request function that is already returning information pertaining to the request

Is there a way to retrieve the data extracted from within newReq.on('response', (response) => {? var request = require('request'); const cheerio = require('cheerio'); const { app, net, BrowserWindow } = require('elect ...

Item on the menu has been pushed lower in the list

There seems to be an issue with the layout of my menu as one item is displaying lower than the others without any clear reason. <html> <head> <title> My Website Homepage </title> </head> <body> ...

a non-breaking space within a hyperlink

While working on the subnavigation of a website, I encountered an issue with the link Suite «Mont Blanc», which was pulled from the backend. The desired format for this link was:       Suite «Mont Blanc» However, t ...

PHP Content File for Dynamic Ajax Website

I recently came across a very informative article that discussed how to create crawlable and link-friendly AJAX websites using pushState. The author provided detailed instructions on the process, but left out a crucial detail - how to store data in a PHP f ...

Steps to make pop-up iframe function on the same page within a react nextjs application

My vanilla Html app has a pop-up feature that functions perfectly. When the button is clicked, the pop-up opens and everything works as expected. However, I am encountering an issue when trying to implement this same functionality in my React, NextJS app. ...

Is there a way to effortlessly launch a new window with just a single click?

I'm encountering an issue with a function that is supposed to open a new window when a button is clicked. Strangely, on the first click, nothing happens, but on the second click, the window finally opens. Here's my code: Script <script src ...

Retrieve SQL data and store it in a JavaScript variable

Need assistance with fetching data from SQL and storing it in a JavaScript variable. I have already connected PHPMyAdmin to my website. I am attempting to retrieve two variables (date) from my SQL table. JAVASCRIPT: var countdown_48 = new Date; countdow ...

Retrieving the value of an inner div upon clicking the outer div

I currently have a collection of button divs, each containing distinct information: <div class="button"> <div id="first"> Johny </div> <div id="second"> Dog </div> <div id="third"> Pasta & ...

Utilize Express and Passport to enable simultaneous login for various 'local' accounts

Apologies in advance for any language or technical errors, as English and Node are not my strong suits. I have resorted to using Google Translation for assistance since solutions within my local sphere are unavailable. EQUIPMENT USED Ubuntu 16.04 locally ...

When attempting to retrieve the data from a JSON file using an XMLHttpRequest, the result that is returned is [object object]

I am currently studying JSON and found a helpful guide on w3schools. Here is the code provided in the guide: https://www.w3schools.com/js/tryit.asp?filename=tryjson_ajax The guide also includes a sample JSON file: https://www.w3schools.com/js/json_demo.t ...

Determine the present height of the current class and substitute it with another class that has the same

My wordpress blog theme has an ajax pagination feature that works well, except for the fact that when a user clicks on the next page link, the entire posts area disappears while the new content is loading. I would like to maintain the same container dimens ...

Using JQuery to conceal floated divs

I'm facing an issue that I had resolved the last time I worked on this website. However, I am currently redesigning it to include additional elements, and I am struggling to make the jQuery part function correctly. Essentially, I have an HTML documen ...

Guide to organizing files with custom directory layout in NodeJS

Imagine having multiple files spread across various folders. /parentDir/ |__dirA/ |__file1 |__file2 |... |__dirB/ |__file3 |... |... You want to consolidate them into an archive, with the option of using something like ...

"Utilizing Bootstrap to create a visually appealing image and text combination in the

I need to arrange the image, first span, and second span in a vertical stack for xs devices. The alignment should be centered for xs devices. If you want to see my code: CLICK HERE <div class="row"> <div> <div class="col-md-9 c ...