We explore how and why Salesforce Lightning Web Components are compartmentalized.
This article is part of the series starting with Exploring Salesforce Lightning Web Components: Part 1.
The Big Idea
Now that we understand that Lightning Web Components are implemented under the hood as Web Components, let us explore the key advantage this affords us; compartmentalization.
To illustrate compartmentalization, we create a CSS file for our helloWorld component:
After deploying the source, we observe that while the page is full of div elements, the only div elements that are impacted by this CSS are those specified in the helloWorld component, e.g., a singular div.
The HTML file, again, with the singular div:
- Notice that the CSS is also not applied to any of the sub-components, e.g., lighting-card, of the helloWorld component
We can see that the CSS is scoped to the Web Component.
Global Window Object
We can see this by setting a property on the window object in helloWorld’s constructor and observing the results:
- Notice, however, that setting a value on window did not cause an exception; rather the window object is different than the global window object. We will explore this later
With Lightning Web Components, being Web Components, we can see that we can “have our cake and eat it too”.
The Lightning Web Component behaves as if it is was part of the DOM, e.g., notice that page automatically responds to the Lightning Web Component’s height.
The historical way to compartmentalize web content was to use an iframe, e.g.,. used under the hood of Salesforce Canvas.
— Salesforce — Introducing Canvas
The problem, however, with the iframe is that has limitations that require work-arounds, e.g., Canvas has a variety of options to handle iframe resizing.
In the next article, Exploring Salesforce Lightning Web Components: Part 3, we explore data binding and related topics.