简体   繁体   中英

DataLayer.push is not working on External JavaScript

If we use dataLayer.push and GTM code in external JavaScript the dataLayer.push value is not firing

In case If we use dataLayer.push and GTM code in HTML the dataLayer.push value is firing as expected

Below is the code which we are used in external JavaScript.

Please let us know if there are any queries

$(document).ready(function() {
    window.dataLayer = window.dataLayer || [];

    function getMetaContent(name) {
        name = document.getElementsByTagName('meta')[name];
        if (name != undefined) {
            name = name.getAttribute("content");
            if (name != undefined) {
                return name;
            }
        }
        return "";
    }
    var countryLanguage = getMetaContent('countryLanguage');
    var pageType = getMetaContent('pageType');
    var audiencePage = getMetaContent('audiencePage');
    var userlogin = "";

    if (localStorage.getItem("login") !== null) {
        userlogin = "identifié";
    } else {
        userlogin = "Non identifié";
    }
    console.log("start");

    window.dataLayer.push({

        'countryLanguage': 'english',
        'pageType': pageType

    });
    console.log("end");

    universal_variable = {
        "page": window.dataLayer
    };

});

You haven't really asked a question with this post, nonetheless, I think I can help, since i had this problem myself.

What I did was put my GTM container snippet in a seperate .js file, and referenced that near the opening <head> tag of the HTML file in question.

Then in another JS file use:

dataLayer.push({'var_name': 'value'});

Make sure this file is referenced AFTER the JS file with the GTM container snippet.

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