How to dynamically add external scripts to Digioh boxes (script src=…)

Sometimes you may want to download an external script to run with one or more boxes, e.g. for third party tracking. If the script is just raw JavaScript, you can paste it directly via Box Custom JS and it will run inside the Digioh box iFrame.

If the script is an HTML script tag like this:

<script src=></script>

Then you have two options:

1) Paste the tag into an HTML block in the specific box

This will download and run the script before the box is displayed. The downside of this approach is that you have to separately paste this into all boxes that require it, so can be tricky to maintain.

2) Add the script dynamically from Box JS
This is the recommended option as it gives you more control as to exactly when the script activates (e.g. After (iFrame) DOM Ready or After Submit, say) and is easier to maintain. There are nuances to adding scripts dynamically via JavaScript, for example it is unreliable to do so using jQuery. We recommend the following JavaScript pattern as best practice:

var e = document.createElement('script');
e.type = 'text/javascript';
e.async = true;
e.src = '';  //URL for the external script
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(e, s);