Exploring Salesforce Lightning Web Components: Part 2

We explore how and why Salesforce Lightning Web Components are compartmentalized.

Image for post
Image for post

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.

Scoped CSS

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.

Image for post
Image for post

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

Likewise the JavaScript is compartmentalized. We observe that code within a Web Component does not have access to the global window object.

We can see this by setting a property on the window object in helloWorld’s constructor and observing the results:

Image for post
Image for post


  • 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

The Win

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.

At the same time, Lightning Web Components are compartmentalized, i.e., both the CSS and JavaScript are scoped to itself. This means that Lightning Web Components cannot negatively impact other elements on the page (and visa-versa).

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.

Next Steps

In the next article, Exploring Salesforce Lightning Web Components: Part 3, we explore data binding and related topics.

Written by

Broad infrastructure, development, and soft-skill background

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store