Reputation: 45
I'm trying to change some of the page html content according to specific query string using javascript fired by Google Tag Manager.
The issue - that it not stable, it works sometimes and shows the pic and sometimes it doesn't for no reason.
HTML
<style>#dc {display:none;}</style>
<img id="dc" class="alignleft wp-image-2685" src="/someImage.png" width="269" height="400" />
JavaScript
<script type="text/javascript">
$(document).ready(function() {
$('#dc').show();
}
);
</script>
I've tested if the Tag is firing and all, and it fires correctly (when querystring dc=1), here is the trigger:
Anyone has any idea why it's not working stably? how can I fix it?
Upvotes: 0
Views: 2313
Reputation: 209
The reason why it works in Firefox and not Chrome might be a result of the tailing feature that Firefox has implemented since version 57. It delays the loading of tracking scripts (up to 6 seconds) until your other scripts are loaded. Thats why jquery is loaded before your tag as mentioned by Max.
Upvotes: 0
Reputation: 13334
It seems you have a race condition: the GTM tag seems to be firing in some cases before jQuery is loaded (hence the $ is not a function
error, because $
doesn't exist at the time the tag is executed, the reason why only with Chrome and not Firefox is because not all browser behave the same :)).
What you can do is insert the following script in your code after jQuery
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
dataLayer = window.dataLayer || [];
dataLayer.push({event: "jquery_loaded"});
</script>
Then create a GTM trigger using that custom event:
And replace the DOM Ready
trigger with that one.
If you have a race on 2 conditions (jQuery loaded and some content being loaded dynamically), then you can write a small loop with setInterval which fires a GTM event (to be used as trigger) when both conditions are met.
Upvotes: 1