My goal is to load javascript in the <head>
only if a certain element exists in the <body>
.
However, I have a problem: I am loading a Web Component, which is just a <script>
hosted elsewhere and is pulled in as:
<script src="https://someurl.com/some-web-component.min.js"></script>
This web component file is huge, so I don't want to pull it in unless it is inserted into body by our Content Management System (CMS).
The constraints I am working under are:
• The <head>
is shared between pages, so I need conditional logic
• I have no control over the <body>
inserted by the CMS, which will potentially contain the <my-web-component>
tag
• I NEED the script to load the web component, so I can't use jQuery's $(document).ready, at least I think I can't - an error will be thrown because the browser won't know the element exists
This plunker partially shows my problem, minus all the web component complexity:
Any way around this?