You'd need to provide more code/details about your Widget and where the above script is running to get detailed answers.
However, all Widget/Section HTML is rendered asynchronously on the client-side when in the Page Builder UI in the Administration application.
Here's the lifecycle of a Page Builder Page:
- Page is rendered via ASP.NET Core (without any Page Builder component HTML)
- Browser receives HTML and executes Xperience Page Builder JS
- Xperience Page Builder JS makes XHR requests back to ASP.NET Core app for Page Builder component HTML (this happens in parallel for all Editable Areas defined on a Page)
- HTML is returned for Sections/Widgets and the Editable Area markers are replaced with this HTML
- When executing in 'Page Builder' mode, the Widget/Section View should execute the JS when the Widget/Section is added to the Page
- When executing in 'Preview' or 'Live' mode, the Page executes the JS when the DOM is loaded