Javscript onload in LWC

i have a requirement to call a javascript method on load of the template.

is there any way to do that in LWC?


Replace an init event handler in an Aura component with the standard JavaScript connectedCallback() method in a Lightning web component.

We use the init event in an Aura component to initialize a component after component construction but before rendering.

<aura:handler name="init" value="{!this}" action="{!c.doInit}"/>

The doInit function in the component’s controller performs any necessary initialization.

    doInit: function(cmp) {
        // initialize component

In a Lightning web component, use connectedCallback() instead in the component’s JavaScript file.

// mySampleInit.js
import { LightningElement } from 'lwc';
export default class MySampleInit extends LightningElement {
    connectedCallback() {
        // initialize component

Also, read this:- Run Code When a Component Is Inserted or Removed from the DOM

if you are intending to use renderedCallback, You should know that, it will fire after connectedCallback and also it may fire more than once(whenever the component rerender itself).

Source : Link , Question Author : Sandeep Chilakala , Answer Author : sanket kumar

Leave a Comment