Exploring Salesforce Lightning Web Components: Part 2

John Tucker
3 min readMay 5, 2019

--

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.

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.

The HTML file, again, with the singular div:

Observations:

  • 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:

Observations:

  • 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.

Canvas enables you to easily integrate a third-party application in Salesforce. Canvas is a set of tools and JavaScript APIs that you can use to expose an application as a canvas app. This means you can take your new or existing applications and make them available to your users as part of their Salesforce experience.

— 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.

--

--

John Tucker
John Tucker

Written by John Tucker

Broad infrastructure, development, and soft-skill background

No responses yet