What is the best practice for using templates in a constructor versus connectedCallback?

Should I apply template in the constructor or connectedCallback of a custom element? In my experience, when I apply it in connectedCallback, sometimes attributeChangedCallback is called before and I can't query for elements.

export class TestElement extends HTMLElement {
  constructor() {
    super();
    //apply template here ?
  }

  connectedCallback() {
    //apply template here ?
  }
}

I'm curious to understand where and why it's better to apply the template.

Here is an example snippet of applying the template:

let t = document.createElement('template');
t.innerHTML = require('template.html');
this.appendChild(t.content.cloneNode(true));

Answer №1

If you opt not to utilize Shadow DOM, refrain from inserting the template in the constructor() callback.

Instead, ensure that you append it only within the connectedCallback().

In any case, attributeChangedCallback() may be invoked either before or after the aforementioned callbacks based on how your custom element is utilized. It is advisable to conduct a test prior to attempting to query inner elements.

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

Unusual issue in IE causing rendering problems in reporting services

Currently, I am creating a report using Reporting Services 2008, MVC 2, and Ajax as my development technologies. When I generate the report, everything displays perfectly if there is data present. However, if there is no data, the report body gets cut off ...

Tsyringe - Utilizing Dependency Injection with Multiple Constructors

Hey there, how's everyone doing today? I'm venturing into something new and different, stepping slightly away from the usual concept but aiming to accomplish my goal in a more refined manner. Currently, I am utilizing a repository pattern and l ...

If the condition has a class name of condition, then display

Having performance issues due to slow data rendering with each tab using a partial view. The code snippet for each tab is as follows: <div class="tab-content" ng-controller="MyController"> <div id="tab-1" class="tab-pane fade active in " ng-i ...

Handling Removal of Selected Option in React Material-UI Autocomplete Single Selection

I am currently using material UI autocomplete to create a single-select dropdown. However, I have encountered an issue wherein the onChange event does not get triggered when I click the close button on the right side of the input. This prevents my state fr ...

Issue with the gulp-babel plugin: Files within the Plugin/Preset should only export functions, not objects

I have started to integrate JavaScript 2015 (ES6) into my Ionic v1 app: package.json { "name": "test", "version": "1.0.0", "dependencies": { "@ionic-native/deeplinks": "^4.18.0", "cordova-android": "7.0.0", "cordova-android-support-gra ...

Determining the Percentage of a Bar Chart

When utilizing Chart.js along with the fork available at (https://github.com/leighquince/Chart.js), I successfully developed a bar chart featuring 3 bars: Goal, Actual, and Available data. My challenge lies in finding a method to calculate the percentage ...

Exploring the possibilities of using the typeof operator within an Event

I want to log some information if the input value is a number. However, I am facing an issue where it's not working and no bugs are appearing. Here is a snippet of code from CodePen (https://codepen.io/matoung/pen/KBNmPP) let button = document.que ...

Guide on using JSZip and VUE to handle an array of promises and store them in a local variable

My lack of experience with async functions has me feeling a bit lost right now... I'm attempting to loop through files in a folder within a zip file using JSZip, store these files in an array, sort them, and then save them to a local variable for furt ...

The icons from FontAwesome in Vue do not update when computed

I am seeking a way to dynamically change the header icon based on a conversation property. <a class="navbar-item" :title="$t('header.lock')" @click="makePrivate"> <i class="fas" :class="getLockClass"></i> </a> These ...

Exploring the power of internal linking with GatsbyJS

I am currently developing a website using gatsbyjs. I have concerns about the crawlability of "onClick" for SEO purposes and I would appreciate some assistance. This is my current code: render={data => ( <div className='feed'> ...

Wizard for the advanced tab panel

I am facing a challenge with my advanced TabPanel Wizard. It consists of 4 tabs, each serving as its own form to allow for validation within the tab itself. The issue I am encountering is related to the validation behavior of non-rendered tabs. One proble ...

Steps to invoke a function to add an element into a list

Every time a user clicks on a button, I want to generate a new tab. In this tab, when the user clicks again, I want a function to be called like: onclick('+reportname+','+report type+') onclick("'+reportname+'","'+repor ...

Is it possible to protect assets aside from JavaScript in Nodewebkit?

After coming across a post about securing the source code in a node-webkit desktop application on Stack Overflow, I began contemplating ways to safeguard my font files. Would using a snapshot approach, similar to the one mentioned in the post, be a viable ...

Combining two numbers retrieved from Firebase using React

Hello, I am new to React and finding it challenging to perform mathematical calculations with React. I have been attempting to add two values retrieved from a Firebase database, but they keep displaying as strings without adding the actual values together. ...

What steps should I take to ensure my mineflayer sprints while trailing behind me?

I am developing a Mineflayer bot that follows me and tries to attack me. However, when I move far away from the bot, it stops following me. In addition, the bot has another issue where it falls while bridging due to its lack of intelligence. How can I im ...

The largest contentful paint is anticipating an unidentified event

My website is encountering issues with Google Pagespeed and I'm unsure of the cause. The primary bottleneck appears to be the LCP time, which Google reports as taking between 7 and 11 seconds during each test. Upon analyzing the waterfall chart, it ...

searchByTextContentUnderListItemAnchorTag

I would like to utilize the getByRole function for writing my test. However, I am encountering issues when using linkitem or 'link' as the role. It seems that I cannot find the desired element. // encountered error TestingLibraryElementError: The ...

Tabs within the AutoComplete popup in Material-UI

Would it be feasible to showcase the corresponding data in the AutoComplete popover using Tabs? There could be potentially up to three categories of data that match the input value, and my preference would be to present them as tabs. Is there a way to in ...

What exactly is the functionality of the jQuery.on() method?

I am curious about the functionality of this function and how it operates. Does it follow these steps: Identify element(s) using their selectors Assign event-handlers to them Execute a setInterval on that selector, consistently delegating and then undeleg ...