Is it possible to enable JavaScript in the shadow DOM? I've tried the below and it isn't working. If not, what are the alternatives:
@Component({
selector: 'app-website-layout',
templateUrl: './website-layout.component.html',
encapsulation: ViewEncapsulation.ShadowDom
})
export class WebsiteLayoutComponent implements OnInit, AfterViewInit {
private static appendCssToShadowRoot(shadowRoot, src) {
const link = document.createElement('link');
link.setAttribute('rel', 'stylesheet');
link.setAttribute('href', src);
link.setAttribute('type', 'text/css');
shadowRoot.prepend(link);
}
private static appendJs(src) {
const script = document.createElement('script');
script.src = src;
document.getElementsByTagName('head')[0].appendChild(script);
}
ngAfterViewInit() {
const shadowRoot: DocumentFragment = this.element.nativeElement.shadowRoot;
WebsiteLayoutComponent.appendJs('https://code.jquery.com/jquery-3.4.1.min.js');
WebsiteLayoutComponent.appendJs('https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js');
WebsiteLayoutComponent.appendJs('https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js');
WebsiteLayoutComponent.appendCssToShadowRoot(shadowRoot, 'assets/css/website.css');
WebsiteLayoutComponent.appendCssToShadowRoot(shadowRoot, 'assets/css/page.css');
WebsiteLayoutComponent.appendCssToShadowRoot(shadowRoot, 'assets/css/fonts.css');
}
}
I've also tried the below, and it doesn't work
private static appendJsToShadowRoot(shadowRoot, src) {
const link = document.createElement('script');
link.setAttribute('src', src);
shadowRoot.prepend(link);
}
WebsiteLayoutComponent.appendJsToShadowRoot(shadowRoot, 'assets/js/popper.min.js');
WebsiteLayoutComponent.appendJsToShadowRoot(shadowRoot, 'assets/js/bootstrap.min.js');
WebsiteLayoutComponent.appendJsToShadowRoot(shadowRoot, 'assets/js/jquery.min.js');
However, I can confirm that the the following does
WebsiteLayoutComponent.appendJsToShadowRoot(shadowRoot, 'assets/js/test.js');
where the content of test.js is
alert('hello');
Stramgely enough it doesn't work for jquery and bootstrap, even though I see them in the HTML source.