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.

IMPORTANT: make sure you really need to add a script to the Digioh Box iFrame. 3rd party scripts may expect to be running in the main window, and might not operate as expected in an iFrame. In addition, Digioh form submission is not a “standard” process, so 3rd party scripts that claim to detect form submissions may not work properly. Generally, we recommend installing scripts to your main page, and they can be invoked from Custom JS using window.parent.scriptFunction. Contact Digioh support for more info.

If the script is an HTML script tag like this:

<script src=https://vendor.com/js/script.js></script>
Then you have three 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 = 'https://www.somefile.com';  //URL for the external script
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(e, s);