How the Shadow DOM has Got You Covered?

Rate this content
Bookmark

We learn about possibilities of what DOM can do but have you ever wondered what all possibilities Shadow DOM can have. Well, In this talk I will help you understand how the Shadow DOM has got you covered. We will further deep dive into how you can use React with Web Components.  

Mukul Ramchandani
Mukul Ramchandani
18 min
12 Dec, 2023

Comments

Sign in or register to post your comment.

Video Summary and Transcription

The Shadow DOM allows for encapsulation and composability, enabling elements to have their own features without affecting the rest of the webpage. Custom elements in the Shadow DOM have their own behavior through encapsulation and scoped styles. Composability is key in software development, allowing for dynamic data passing. The Shadow DOM provides a way to modify the appearance of elements within it, but some properties are marked as important and cannot be changed. Building a Chrome extension using the Shadow DOM allows for composable and encapsulated experiences.

Available in Español

1. Introduction to Shadow DOM

Short description:

The Shadow DOM is a hidden DOM tree that behaves differently from the Light DOM. It allows for encapsulation and composability, enabling elements to have their own features and functions without affecting the rest of the webpage. The Shadow DOM is different from the Light DOM in how it is created on a specific element. It provides a way to encapsulate elements, similar to how different pizza slices have their own toppings. This allows for better organization and separation of functionality.

So, hello everybody. As you can see, the title of the talk, it's how the Shadow DOM has got you covered. Not, not has it ever got you covered. It has got you covered. And in the the hindsight, for sure. So in this Lightning Talk, we're going to see like how it has got you covered.

So let's let's start with the talk. So, hey, everyone. I'm Mukul and I'm working as a front-end engineer at Hubilo. Apart from work, I like, I'm very passionate about indie music, board games and who is not passionate about traveling? So yeah, what is Shadow DOM? To define it simply, it's a normal hidden tree, hidden DOM tree with differences in how it behaves with the rest of the Light DOM. So given to the context of the talk, the DOM we interact on a daily basis. We add, we append, we remove elements. It's a normal DOM, right? And the DOM that we are going to talk about, we are going to refer that normal DOM as a Light DOM and the DOM that we are going to talk extensively about is the Shadow DOM. So as you can see on the screen, like this text is in the Shadow DOM. You can see it is a placeholder text, right? Whenever you try to inspect this and when you try to find out, you usually don't find this specific text written anywhere in the DOM, but it is present, very present. It's present in the Shadow DOM. While this is another example, like if you see a choose file button, someone must have written a button CSS of it and how this element should come in the inline and the code. What should happen when someone clicks on the choose file button, but all we do is we type input type file and then magic happens and this element appears. But the whole CSS of this has been written somewhere in the Shadow DOM. So, yeah, so let's just move further to know more about the Shadow DOM.

So how it's different than the Light DOM? So as I said, Light DOM is the normal DOM and how it's different from that? So very first thing, it is different on how this specific Shadow DOM is created on a specific element. So for example, let's say there is an element called as, let's say a div element, but you want the shadow element to that development you can create it. So the way you create and you use it, it differs in that area. Another very amazing and one of my favorite features which Shadow DOM brings in is encapsulation and composability. So think about this, like think about this, like, let's say you're eating a pizza and on one slice of pizza you basically get all your veggies, all your, all your toppings on one slice. Another slice would have its own set of toppings. So it's kind of those pizza slice has everything in it encapsulated. So in the same manner, Shadow DOM has its property of encapsulation and composability. Having its own way of features functions and ability to perform on its own and instead of disturbing the rest of the functionality on the webpage. If we talk about the precedence, let's say an element having a normal DOM and a Shadow DOM.

2. Shadow DOM and Web Components

Short description:

Shadow DOM has a greater precedence than Light DOM. Some HTML elements have their own Shadow DOM, like Textarea, Choose File Button, Video, and Audio. These elements come with pre-built functionality and styling. However, not every element has its own Shadow DOM. To leverage the benefits of Shadow DOM, we can create our own elements, like a custom button, using web components and the Shadow DOM API.

So Shadow DOM is usually given a preference. Shadow DOM has a greater precedence than Light DOM is one of the another difference when compared with the Light DOM. Cool, moving on so but not everyone has its own Shadow. Like we took the example of Textarea, we took the example of Choose File Button. There are other examples like Video and Audio. If you see Video and Audio elements, they have a plus button, they have a Seek bar, they have a Options button, all those elements come handy to us. We just add a video tag and they just appear. So someone must have written a CSS and the complete code and complete functionality of it. So that all resides in the Shadow DOM. And the Select option, the dropdown, the CSS around it, all that resides into a Shadow DOM. But not every element in the given HTML elements has its own Shadow DOM. For example, a div element, for example a span element doesn't have its own Shadow DOM. So we need to dive deeper on how we can get the benefits of the Shadow DOM on the way we want it, the way we want to encapsulate it, the way we to add a composability in nature to our HTML elements.

So one of the ways where we can create a Shadow DOM, so let's say there is an element called a header and let's say we want to attach Shadow with mode open. This is a browser API that is available, Attach Shadow, which helps us basically attach a Shadow DOM and once, attach a Shadow DOM to the element that we just created, a header, and with this header what we can do is we can add an inner HTML and add a like Hello Shadow DOM and that would be added to that element as a Shadow DOM. We are gonna look into it very soon on how it appears in the browser. But that is not it right. If you think about it here, we don't want to attach Shadow DOM to the existing elements. We can have their own, because they have their own properties, they have their own way of behavior as per the element, for example input, header, H1, H2 tags, and whatsoever. Every element has their own behavior. So we don't want to hinder that. Instead we would like to use the Shadow DOM by creating something of our own. Like let's take the example of a button. Like let's say you want to have a button where it has its own way of behavior, own way of animation, own way of giving way of title to button. So hence, Shadow DOM, when we talk about the Shadow DOM, we have to bring picture, we have to bring web components into the picture. So web components. Today we are going to look into the web components from little from the Shadow DOM perspective instead of like bringing up re-usability point of view. That aspect would be covered a little bit as well. So if you think about, so if you see how I can create a web component, basically a web component, a complete custom element of my own, like let's say I want to create my cool button, my cool button, and if I want to like put anything here, how would I go about it? I would just create a class. I would disconnected callback and disconnected callback would be the functions like, yeah, now that we are in the react event, so connected callback is basically when something is mounted in the DOM and disconnected callback is when the element is unmounted in the DOM, so you get this callback and based on this callback, you can add listeners, you can add CSS, you can add whatever you want and you can add a behavior to it using this DOM.

3. Custom Elements and Encapsulation

Short description:

Custom elements in the Shadow DOM have their own behavior through encapsulation. The shadow root, attached to the web component, contains its own styles. This allows for scoped DOM and scoped styles, ensuring that the styles and behavior of the custom element do not interfere with other elements on the webpage.

So I can just define custom elements or define my cool button and that will be available for a browser to render, like my cool button, and we'll be able to use this, our custom element and it will have its own behavior, but how would it have its own behavior? We would need to add encapsulation to it, right? So if you see encapsulation, I've been repeating this word a lot, but this is one of the very interesting features of the Shadow DOM.

So what encapsulation brings in is scoped DOM and scoped styles. So if you see here, this shadow root, when I, in the constructor, when I'm initializing my web component, there's a shadow root. I'm attaching a shadow to it, and to that shadow root, in the inner HTML, what I'm doing is I'm giving the style on its own. So if you see here, I'm giving very generic names. I'm giving main, main hover. So if you think about this, like main can be a class that is available on the webpage to any other element, to any other parent element. But would that create a problem with this? The answer is no. Because shadow DOM has a property of encapsulation and composability. So if you see here, I can give such classes, I can give styles, and I can use those styles here in the dev element. And what would happen with that is what would happen with this dev element where my button is written, can have its own styles, can have styles of its own like scope DOM and scope site. So yeah, moving on.

4. Composability and Data Passing

Short description:

Composability is key in software development. It allows components to be powerful by enabling data to be passed dynamically. Just like in React, where data is passed using props, web components have slots that allow data to be passed. Slots provide a way to have fallback content in case data is not passed. By passing a name in the web component, it can be displayed in the slot, with a fallback option if no name is provided.

Composability. Composability. So every component becomes powerful when you are able to pass the data. So as you can see, let me go to the previous slide, as you can see here, it's written dev my button. But how about an ability to change the name of the button dynamically? Like I want to use this component, I want to use the styles, I want to use the appearance of this, but I just want to keep changing the name of the button, like whatever the title of the button is, can you do that? Yes. And that brings the composability, which to, so, so just a question. I mean, I would, like just a question for I'm sure, you know, this answer, like how do we pass the data into the components by the, by via using react? The answer is props, right? So, so in the same manner we have for your slots, so slots allows us to pass the data into our web components. And with that we can, we can have with that, we can have our shadow down to have its own styles and behavior, right? So if you see your slot, I'm passing a name icon and, and, and with that, you can see that I'm giving a fallback as well. Let's say our data is a data is not passed, right? So, so you can see that in inside the slot I can have a fallback content and, and, and, and yeah, I mean and, and if I say like slot name title, so I can have a fallback name. So, so all I have to do is I have to pass the name, a name in the web component and that would appear here. Otherwise the fallback would appear if I'm not passing.

5. Exploring the Shadow DOM

Short description:

Looking into the shadows is important. I have three generic HTML elements: a text area, a file chooser, and a dropdown, as well as a custom button. By accessing the shadow DOM, I can modify the appearance of elements within it. However, some properties are marked as important and cannot be changed. The same applies to other elements like title and select. My custom button has a slot named 'title' where I can insert content.

Cool. Moving on, moving on. Before we move on to this finding purpose slide, I want to quickly show you like how you can look at the shadow DOM. Looking into the shadows is kind of the one of, one of the very important thing.

So as you can see here, I have a very three generic HTML elements. One is a text area, another is file, file choose another is a dropdown and one, I have a very interesting button that is a custom button that I've created.

So I will just create a, I'll just go here. I'll go, go in the settings, you can see the settings tab. I'll click on here and you can see that here, when I go in this elements thing in the preference site, you can see that show user agent shadow DOM. If I click on this check mark this, and if I close this, if I go here and if I select this thing, you can see here that I something appears here. Like you can see that this, it is, it is something called a shadow root.

And in that shadow root, you can see that a pseudo, a pseudo selectors where we can change the color of this text like this text is in shadow DOM. And you can simply like, like, like I can simply do C-U-L-O-R color blue. You can see that the placeholder of the color, the color of the placeholder changes to blue, uh, which is something residing into the shadow DOM. Uh, but, but you cannot really change the display of this because, because it is given an important. Yes, while I open into the browser you can do it, but from the code point of view you cannot, but if something is given important into the shadow DOM, it is important. I mean, I mean that is something you cannot change it.

So it also gives a very interesting way to log few of you wanted. Uh, if you want some behaviors to it. Cool. In the same manner, if you, if you look at this element like title, uh, in the same manner, like if I, if I click here, if I go here in the, in the shadow DOM, you can see that there is a button, there is a shadow road, which, which, which gives the button of this choose file return. And you can be, we can also change the text if we want. So moving on, same goes for the select. But here's one of the interesting thing here is my button. You can see that here. I've created HTML element called this my button. And here I have given a slot. I've given a slot called as title. So how I have defined this, what I've given a span element inside the my button, inside the my button. If I click on the my button, you can see in the my button, I've written a span with slot title, and I have given a element that does title.

6. Exploring Shadow DOM and Encapsulation

Short description:

The slot inside the shadow DOM takes the name of the passed element. For example, passing a title to a button will display the title. Without passing a title, the fallback name 'button' is displayed. Encapsulation includes style, initial state, and the entire DOM.

So what it does is you can see there is a slot here, which takes me inside the shadow DOM. And it says that whenever you pass something with the slot, it will have this written as ... it will take its name. So just to take another example here, just to test out this example, you can see that I'm passing your title. In this my button, I'm passing a title. If I just remove it, what if I don't pass this at all? I'm just passing a my button. And the moment I refresh it, you can see before that it was title and now it became button ... because the fallback that I've given me, fallback name I've given is button. And further you can see that I've encapsulated style, initial state and I've also encapsulated the dom completely.

7. Building a Vocabulary Assistance Chrome Extension

Short description:

Let me show you what I've built and you can build it very easily. We're going to build a vocabulary assistance Chrome extension that can be used across the web. By injecting code into any webpage, we can select a word and have its meaning appear right there. The extension uses the shadow root to insert the response and has its own composable nature.

But yeah, I get your point, you're like Mukul, fine, this is cool but where would I use it? So this is one of the very interesting thought I found. Knowledge is knowing that a tomato is a fruit, wisdom is not putting it in a fruit salad. Let me show you what I've built and you can build it very easily. So what we're going to build is ... we'll check out this build mode and share the repo.

What we're going to build is ... so as a kid I always wonder like whenever I'm reading on the Internet, I just want to select a word. I want to select a word and whenever I select that word, I want to have the meaning of that word. The moment I select a word, my meaning should appear right then and there whatever the webpage is, whichever the webpage on however it is. So basically what I would need to do is I would need to inject a code inside any other webpage. And with that, I want to use that. So how I've done this? I've created a very, very small extension. You can see that it's a very ... you can see here that the class meaningful, so the Chrome extension that the name I've given is meaningful. And what you can see is here this is available your vocabulary assistance anywhere on the web, but it may seem like it's something complex, but I'll show you how in just a few lines of code, you can literally build a vocabulary assistance and that can be used across the web.

So you can see that the ... here I'm doing inner HTML. Here I'm doing ... attaching style tags and here I'm doing ... and here I'm using the ... simply using a huge ... I'm using a word meaning, which basically fetches me a word whenever I select for it. Whenever I select for it, the moment I select that word, I'm just inserting those ... whatever the response I've got ... inside the shadow root. Now that it has my own styles, I can access those get element by ID because it has its own composable nature, right? It completely own doc, scope doc. I'm just appending the data that's coming into the response and after that there is a selection change where user selects a word and we want to show the meaning. It calls the API using a suite debounce function here so that whenever we want ... so that Multiple Select Event doesn't call the multiple APIs and here, whenever word is selected, we keep the opacity one and whenever the selection is removed, we would remove that opacity. As I said, this is something you can surely look into it.

8. Diving into Shadow DOM

Short description:

You can dive into the code and see a demo on GitHub. By selecting a word, you can see its meaning appear. To build similar experiences, use a shadow DOM with complete composability and its own style and div. Shadow DOM provides encapsulation and composability, which are key features for building interesting applications.

You can dive into the code. So let me quickly show you the demo of this. So let's say I'm on the GitHub and let's say I'm on ... where am I? Okay, so I'm just ... so if I just click on a road map, you can see something ... you can see a pop-up loads up, road map, a map with a visual representation. You can see that. We can clearly see the meaning of it. So if I select this word and you can see the meaning appears of optimization, fundamentals, right? A meaning appears. So experiences like this.

If you want to build experiences like this, what would you use? You would use something like a shadow DOM. So you can see here, if I go here, you can see that the only thing that I have that I'm injecting is meaningful, which is the name of the element, HTML element. And in that element, I have complete composability of my shadow route and it has its own style. It has its own div, composability of its own. So yeah, I think I really hammered on composability and encapsulation a lot. And as one of the very interesting features, one of the very interesting application that I showed you, like how you can use encapsulation and composability.

So that's about it. And that's how Shadow DOM has got you covered. We may not notice it, but at some point, it has got us covered. So that's about it.

Check out more articles and videos

We constantly think of articles and videos that might spark Git people interest / skill us up or help building a stellar career

It's Time to De-Fragment the Web
React Day Berlin 2022React Day Berlin 2022
34 min
It's Time to De-Fragment the Web
Top Content
Over the past few years, the number of web frameworks available to us has exploded. In some ways, the breadth of choice is a clear win for our ecosystem. However, for many of us, it also comes with harsh drawbacks: - Have you ever used a popular open-sourced component built for framework A, and wished it existed in framework B? What about a design system library? - Does your company have frontends built in different frameworks, and your web teams are frustrated about the wasted hours needed to achieve a consistent design system? - Does your team build SDKs for web frameworks, and must manually re-write them for each framework? The solution to all 3 of these problems exists today. To fully understand it, we must first examine today’s web frameworks, re-think what a component should look like, and introduce a new Intermediate Representation of our components. This is what we have done at Builder.io when we created Mitosis, and we’re excited to share it with everyone.
The Good, The Bad, and The Web Components
JSNation 2023JSNation 2023
29 min
The Good, The Bad, and The Web Components
Top Content
There has been no shortage of both fair and unfair criticism toward Web Components from a wide range of folks that build for the web, including but not limited to JavaScript Framework authors in supposed competition with the platform. In this talk I'll show you how to navigate and simplify the multifaceted landscape of web components, satisfying common criticisms and showing how you can Use the Platform most effectively today.
Web Components, Lit and Santa 🎅
JSNation Live 2021JSNation Live 2021
28 min
Web Components, Lit and Santa 🎅
Get started with Web Components – enabling you to define new HTML elements that work everywhere regular HTML does. This talk will focus on Lit, a suite from Google that helps you create WCs with features you'd expect like data-binding and declarative definitions. It'll also cover how we've used them to build one of the web's jolliest sites, Google's Santa Tracker 🎅
Authoring HTML in a JavaScript World
React Summit US 2023React Summit US 2023
21 min
Authoring HTML in a JavaScript World
 In this talk, Tony shows how an authoring and semantic HTML-first approach to JSX template work leads to more readable, maintainable, and accessible UI components. He demonstrates how to think through implementing a UI prototype in a semantic way, authoring HTML before visuals. He shows how accessible markup improves performance, reduces DOM size, minimizes time spent on CSS, and reduces cognitive load not only for developers, but also for all our users, no matter how they consume our sites and applications.
Immutable Web Apps
JSNation 2022JSNation 2022
20 min
Immutable Web Apps
Resolving dependencies when they are all bundled together is easy. Resolving dependencies when they are in being loaded via script tags is much more challenging. The goal of this talk is to explain how Meltwater handles dependency resolution when building native Web Component based applications that rely on packages published by many different teams.
Web Components are awesome!
JSNation 2022JSNation 2022
10 min
Web Components are awesome!
Ever wondered how by placing "video" or "audio" into your HTML, you get a media player with controls included? Or how, depending on the type attribute, "input" can be a button, a place to enter text, select a date or file, color picker and more? What if you could create your own element? The answer: Web Components! 🤯 In this talk, we’ll take a look at what Web Components are, how to make one and include it into an application.

Workshops on related topic

Web Components in Action
JSNation Live 2021JSNation Live 2021
184 min
Web Components in Action
Workshop
Joren Broekema
Alex Korzhikov
2 authors
The workshop extends JavaScript programming language knowledge, overviews general software design patterns. It is focused on Web Components standards and technologies built on top of them, like Lit-HTML and Lit-Element. We also practice writing Web Components both with native JavaScript and using Lit-Element. In the end we overview key tooling to develop an application - open-wc.