Closed kingo55 closed 10 months ago
@kingo55 To do this, we need the following snippet:
<script type="text/javascript">
if (!window.Mojito || !Mojito.testObjects || !Object.keys(Mojito.testObjects).length) {
var po = document.createElement('script');
po.type = 'text/javascript';
po.async = false;
var stags = document.getElementsByTagName('script');
var s = document.getElementsByTagName('script')[stags.length -1];
s.parentNode.insertBefore(po, s);
po.src = '//hostname.com/path-to/mojito.js';
}
</script>
It prevents from loading the JS file twice.
Thanks @allmywant - I might update these docs to reflect that then.
What does || !Mojito.testObjects || !Object.keys(Mojito.testObjects).length
do in the check here and in the one in the library?
@kingo55
|| !Mojito.testObjects || !Object.keys(Mojito.testObjects).length
it checks if Mojito has test objects loaded. For example:
If we call Mojito.addTest({ test object })
in the container, then the check returns false. In other word, it checks if the container is empty (without test objects loaded).
Cheers @allmywant - that makes sense.
@dapperdrop @allmywant - related to https://github.com/mint-metrics/mojito-js-delivery/pull/111 - When installing the snippet, we often recommend this approach to clients:
Via: https://mojito.mx/docs/js-delivery-hosting-snippet
Obviously we can't easily fix containers already implemented on clients' sites with this method, but going forwards, should we consider updating the snippet installation? I.e. Check before loading it into the page.
For SPAs this might prevent it from loading the JS file twice, right?