0

I've created a shadow dom in javascript and everything is working as intended. Except, I want to add a remote JS script to it and consume a function it contains. But don't know how to do this.

This is an piece of code I use for the creation of my shadow DOM:

var shadowDom = this.attachShadow({ mode: 'open' });
var html = "<div class='stuff'>Hi!</div>";

let wrapper = document.createElement('div');
wrapper.innerHTML = html;

const js = document.createElement('script');
js.setAttribute('src', 'http://mywebsite.com/js/code.js');

shadowDom.appendChild(js);
shadowDom.appendChild(wrapper);

The code.js script includes:

function test()
{
    alert("ok");
}

How can I call the test() function once I've added the code.js to my shadow DOM inside my widget's script?

Thanks

jennie788
  • 396
  • 3
  • 18
  • Script runs in global scope; so there is no need to append the JS code to shadowDOM, you can append it to the HEAD or BODY. Then use the ``onload`` event to trigger code once your external script has parsed; see: https://stackoverflow.com/questions/16230886/trying-to-fire-the-onload-event-on-script-tag – Danny '365CSI' Engelman Oct 18 '21 at 09:23

1 Answers1

0

The easiest way to auto call a function is to use the following syntax in your imported code.

function test()
{
    alert("ok");
}()

This should execute the function as soon as the code is evaluated.

Olek Oliynyk
  • 136
  • 3