I am developing a web component using Polymer 2, and would like to make use of a third-party JavaScript library, which was not specifically designed for use with web components. As far as I know, the only way to do this is to include a <script>
tag referencing the library, within the HTML file of my web component.
I can see a couple of issues with doing this, and want to know if there are any ways around them, and indeed whether including third-party libraries in this way is considered bad-practice.
The external library might set global variables which are visible to other components on the page, allowing web components to break each other, or break the page they are hosted on. Since encapsulation is often touted as one of the big advantages of using web components, this seems like a problem.
The external library might perform DOM queries or updates which would not be able to access the shadow-dom of the web component that is using them, so the external library might not actually work at all, or might update the hosting page's DOM again breaking encapsulation.
So, am I missing something or does this mean that including external libraries in a web component is a really bad idea? If so, it seems like a huge limitation of this technology, since we can't take advantage of the vast number of pre-existing JS libraries out there.
To include an external JavaScript file, we can use the script tag with the attribute src . You've already used the src attribute when using images. The value for the src attribute should be the path to your JavaScript file. This script tag should be included between the <head> tags in your HTML document.
Installing the library. Once you have the . js file, you need to put it in the same place as the rest of your project. For simplicity's sake, put it in the same folder that your sketch.
No, you can't do that. The framework will prevent your code from running.
If you have an external library that does things like document.querySelector
then you have two choices.
document
.Beyond those two options you will probably not be able to use a third party library that assumes document
will work for everything.
I guess the other option is to re-evaluate the third party library and see if it is REALLY worth using.
On my team we don't use third party libraries that are not just solid logic. Things like moment.js are just logic and we can use them without problems.
But something like jQuery? Yuck! I can't see needing something like that for a component.
Good luck!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With