简体   繁体   中英

Google Tag Manager not referencing jQuery? "$ is not a function"

Going to start off by saying I have very limited experience with JS and jQuery, so I'm flailing around a bit here.

I've got a GTM custom HTML tag that uses jQuery to grab the text from label/legend elements associated with a specific error message class, and push each one to the dataLayer for event handling:

 <script type="text/javascript" id="error-push"> jQuery( document ).ready(function() { var errMsgs = document.getElementsByClassName("error_message"); for (i = 0; i < errMsgs.length; i++) { var assocLabel = $(errMsgs[i]).closest(".field_error").find(".field_label").text(); if(assocLabel) { dataLayer.push({'field-error': assocLabel}); } } }); </script>

I can get the function to run no problem when tested directly in my browser console. But when I run it via GTM, I get an Uncaught TypeError:

Uncaught TypeError: $ is not a function
    <anonymous> https://example.com/form/?gtm_debug=1661509869380 line 348 > injectedScript:1
    jQuery 2
        e
        t
register:1:218

At first I thought that GTM was just firing the script before jQuery was loaded, so I included an extra line at the top of the script in GTM to check for it:

<script type="text/javascript" id="error-push">
  typeof window.jQuery !== 'undefined' ? console.log(window.jQuery.fn.jquery) : 'jQuery not found!'
  jQuery( document ).ready(function() { ...

...And the console is returning "3.6.0", indicating that jQuery is loaded when the function runs. So where is the TypeError coming from?

My personal practice for Google Tag Manger is not using jQuery within it.

Because it will have so many error that not sure why it comes up.

In your case:

I suggest you use the trigger Dom Ready . From what I know it is quite the same when you want to fire something as jQuery( document ).ready(function() {}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM