asosnovsky
asosnovsky

Reputation: 2235

shadow-root: is there a way to include an external javascript file into a shadow-root?

Say I have a few js-files stored externally, or I just want to load a new dependency like JQuery or Angular in my shadow-root, is there a way to load it into it?

I know for css-stylesheets you can just do:

var style = document.createElement('style');
    style.setAttribute('type','text/css');
    style.innerText = '@import "' + csspath + '";';

is there a similar way to do that with js? Since just doing this:

var script = document.createElement('script');
    script.type = "text/javascript";
    script.src = jspath;

doesn't work :/

Also I am doing this:

var root = document.getElementById('container').createShadowRoot(); 
var DOM = new DOMParser().parseFromString(html.responseText,'text/html').getElementsByTagName('html')[0];

DOM.getElementsByTagName('head')[0].appendChild(script); 

the "parseFromString(html.responseText,'text/html')" is because I am getting my html from an external source as well.

Here is a plunkr http://plnkr.co/edit/YM1lXN8QEhjMd4n9u0wf?p=preview

Upvotes: 5

Views: 5251

Answers (2)

robdodson
robdodson

Reputation: 6786

As you figured out, Shadow DOM does not create a new scope for JavaScript, it's only concerned with DOM and CSS scoping.

There are a couple approaches to adding JavaScript to the document. The first is the classic script injection:

<script>
    var script = document.createElement('script');
    script.src = "//somehost.com/awesome-widget.js";
    document.getElementsByTagName('head')[0].appendChild(script);
</script>

You were doing this in your previous example but you were appending the script to the wrong place. Just add it to the main document instead of the html that you loaded. I think it should work in either instance, but it makes more sense for it to follow the typical pattern of appending to the main document's head.

The other approach, if you're using HTML Imports, is to include a link tag, which has a script that points to your resource. This is often what we do with Polymer elements. We link all of our dependencies at the top, that way they get loaded before our element definition is registered.

Upvotes: 4

asosnovsky
asosnovsky

Reputation: 2235

So I kinda figured this out, I didn't understand what a #shadow-root is. Its not like an iFrame where it gets its own #document and has a completely different environment to the rest of the site. You can load js into a shadow-root by calling its parent element and then its elements, So say this is my structure:

div [id='app']
|   #shadow-root
|   |   div [id='content']

then in order to work some magic on the '#content' tag, using jquery you can change it by doing this:

$('#app').find('#content').html('hello world')

Even if this code is ran from inside the shadow-root

Upvotes: 1

Related Questions