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

Ways to clearly establish the concept of "a"

module.exports.getData = function (id) { const userData = require("./data/Users.json"); if (userData.find(user => user.uid === id)) { return user.name; } else return "User"; } I'm trying to display the name of a user, but the consol ...

Finding the total amount in VueJS2

I'm having trouble calculating the total row in Vuejs2 as shown in the image below: This is the code I have been using: <tr v-for="(product, index) in form.items" :key="index"> <td class="saleTable--td">{{ product.name }}</td& ...

The "maxlength" attribute does not function with the input type "number" in an HTML textbox

The maxlength attribute does not seem to be functioning properly when using type="number" ...

bootstrap-vue tabs - reveal specific tab content based on URL anchor tag

For my SPA, I am utilizing bootstrap-vue and currently working on a page where nested content needs to be placed within b-tabs. If given a URL with an anchor (e.g. www.mydomain.com/page123#tab-3), the goal is to display the content under Tab 3. Query: Ho ...

Tips for eliminating double quotes from an input string

I am currently developing an input for a website that will generate a div tag along with its necessary child elements to ensure the website functions correctly. I have a couple of key questions regarding this setup: <!DOCTYPE html> <html> < ...

Show an image based on a query parameter

Currently, I am developing a PHP project and I am facing an issue with loading an image from a query string. Here is the code snippet I am using: <img src="load_image.php?name=Profile_Photo_Small" /> Is there anyone who can help me out with this pro ...

What is the method for retrieving a temporary collection in a callback function when using node-mongodb-native find()?

Is it possible to retrieve a temporary collection from a find() operation instead of just a cursor in node-mongodb-native? I need to perform a mapReduce function on the results of the find() query, like this: client.open(function(err) { client.collect ...

What is the importance of accessing the session object prior to the saving and setting of a cookie by Express-Session?

Quick Summary: Why is it crucial to access the session object? app.use((req, res, next) => { req.session.init = "init"; next(); }); ...in the app.js file after implementing the session middleware for it to properly function? Neglecti ...

"Any tips on maintaining the blue color of my dropdown link when it is selected as active

I'm struggling to keep the bootstrap accordion dropdown link blue when it's active. I've tried different methods but none seem to work. What am I missing? Here's my code: <div class="visible-sm visible-xs" id="accordion" role="t ...

Utilizing Airbnb's iCalendar Link for Automation

I have obtained the iCalendar link for an Airbnb listing. Upon visiting the link in any browser, it automatically triggers the download of a .ics iCalendar file. My goal is to develop an application that can sync with this specific Airbnb listing's iC ...

"Patience is key when waiting for an AJAX response within a jQuery loop

I've been facing difficulties in making this work using the $.Deferred object. Here is a simplified version of the code setup. g_plans = []; $(function(){ // Need to utilize a custom ajax function that returns a promise object var pageLoadPro ...

The visibility of buttons can be controlled based on the selected radio option

I have just completed setting up 4 buttons (add, edit, delete, cancel) and a table that displays data received via ajax. Each row in the table contains a radio button identified by the name "myRadio". When a radio button is clicked, I need the buttons to ...

Why is my CSS not recognizing the animation I specified for it to play?

I can't seem to get the simple animation I added to my code working properly. <div class="phone-center"> <div class="phone"> </div> </div> .phone-center { display: flex; justify-content: ce ...

Error: Controller not found when angular.module is called from different files

As I am restructuring my code to make it more modular, I decided to move the controller into a separate file that belongs to the same module. However, I am facing an issue where the controller does not load, even though I have verified that the load order ...

creating custom HTML elements in Rails forms

As a newcomer to Rails, I have scoured the internet and books for information on creating custom forms in Rails with no success. I am accustomed to writing my own HTML tags and feel comfortable doing so. I prefer not to rely on libraries like JSF (from JAV ...

Python Automation: Saving Excel Files with Selenium

I'm on a mission to download an XLS file for each day of a specific month. However, when I use Chrome's developer tools to inspect the download button for the XLS file, it turns out that it's not actually a button at all. So how can I go abo ...

Looking for the location of a matching brace in a dataset?

As a newbie in the world of coding, I have embarked on learning about NodeJs file system module. Currently, my focus is on handling a large data file stored as a string. The challenge that I am facing is with locating the matching close brace and its pos ...

Determine the week number based on a specified starting day for the week

If I have a custom week start day other than Monday, how should the getWeekNumber() prototype for the Date class be modified? Here is the existing code for calculating the ISO Week Number: Date.prototype.getWeekNumber = function() { // Create a dupli ...

Encountering problems with ajax technology

As a newcomer to Laravel and Ajax, I am facing an issue with displaying the state of the selected country in a dropdown list. Although the data is successfully fetched from Laravel and received through Ajax, I am struggling to dynamically add it to the H ...

Storing the path of a nested JSON object in a variable using recursion

Can the "path" of a JSON object be saved to a variable? For example, if we have the following: var obj = {"Mattress": { "productDelivered": "Arranged by Retailer", "productAge": { "ye ...