Mobile app version of vmapp.org
Login or Join
Kristi941

: How should I access a variable after an async script is loaded? I have a setup tag for a Tracking service called Clicky that loads asynchronously on every page. I need to access "clicky" variable

@Kristi941

Posted in: #GoogleTagManager #Javascript

I have a setup tag for a Tracking service called Clicky that loads asynchronously on every page. I need to access "clicky" variable from another tag, which is only accessible after setup async script finishes loading.

For that reason, my tag script looks hacky. Is there any other way to check if an async script is loaded on Tag Manager context?

<script>
function clickyGoal() {
try {
clicky.goal('Email Capture');
} catch(e) {
setTimeout(clickyGoal, 200);
}
}
clickyGoal();
</script>


EDIT: This is the main setup tag that fires on all pages.

<script type="text/javascript">
var clicky_site_ids = clicky_site_ids || [];
clicky_site_ids.push(<id-number>);
(function() {
var s = document.createElement('script');
s.type = 'text/javascript';
s.async = true;
s.src = '//static.getclicky.com/js';
( document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0] ).appendChild( s );
})();
</script>

10.02% popularity Vote Up Vote Down


Login to follow query

More posts by @Kristi941

2 Comments

Sorted by latest first Latest Oldest Best

 

@Megan663

In your main set up tag, you should push an event once it has completed loading:

<script type="text/javascript">
var clicky_site_ids = clicky_site_ids || [];
clicky_site_ids.push(<id-number>);
(function() {
var s = document.createElement('script');
s.type = 'text/javascript';
s.async = true;
s.src = '//static.getclicky.com/js';
( document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0] ).appendChild( s );

// push event to dataLayer
dataLayer.push({
'event': 'clicky ready'
})
})();
</script>


In your subsequent tags that require the "clicky" variable, you would just need to add to your trigger the "clicky ready" event.

10% popularity Vote Up Vote Down


 

@Yeniel560

You can use the onload property of the script tag to see when the script is loaded:

<script type="text/javascript">
var clicky_site_ids = clicky_site_ids || [];
clicky_site_ids.push(<id-number>);
(function() {
var s = document.createElement('script');
s.type = 'text/javascript';
s.async = true;
s.onload = function() {
clicky.goal('Email Capture');
};
s.src = '//static.getclicky.com/js';
( document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0] ).appendChild( s );
})();
</script>

10% popularity Vote Up Vote Down


Back to top | Use Dark Theme