Why are you storing CODE in the shadowDOM? Code is not sandboxed like HTML and CSS when inside shadowDOM. It is still run at a global level. This is different than how the <iframe> works.
If you are going to this level of attempted segregation of code then just use a real WebComponent and do everything in that class.
If you still have to continue to do it how you are doing it then you need to have a way to pass variable (The shadowRoot variable) into the code you are placing in the shadowDOM.
UPDATE - Aug 3, 2020
If other code needs to access a closed shadow DOM then the code that created the shadowRoot needs to save off the shadowRoot as a variable and then pass that variable to the other functions. Or, you need to create a closed scope within JavaScript and store the shadowRoot in that scope. If all other functions are within that scope then they will have access to the variable that points to the shadowRoot.
Below is some EXAMPLE code that shows how to create a scope.
const publicInterface = (function() { var shadowRoot; function createShadowDom() { shadowRoot = ... } function doSomethingElse() { let a = shadowRoot.querySelector('.something'); if (a) { } } return { createShadowDom, doSomethingElse } })(); publicInterface.createShadowDom(); publicInterface.doSomethingElse();
The variable shadowRoot is protected inside the scope and can not be accessed by any outside code. But any function inside the scope, like createShadowDom and doSomethingElse can access shadowRoot.