JS附加脚本标签执行

时间:2018-10-03 15:11:09

标签: javascript jquery html

我正在尝试将Google Analytics(分析)标签动态添加到网页中。最初,我使用jQuery来做到这一点,并且效果很好。这就是我的使用jQuery的js:

(function() {
if (typeof window.jQuery !== 'undefined' && typeof window.$ !== 'undefined') {
    var gtmHeadCode = "<!-- Google Tag Manager -->" +
        "<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':" +
        "new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0]," +
        "j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=" +
        "'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);" +
        "})(window,document,'script','dataLayer','GTM-XXXXXXX');</script>" +
        "<!-- End Google Tag Manager -->";

    var gtmBodyCode = "<!-- Google Tag Manager (noscript) -->" +
        "<noscript><iframe src='https://www.googletagmanager.com/ns.html?id=GTM-XXXXX'" +
        "height='0' width='0' style='display:none;visibility:hidden'></iframe></noscript>" +
        "<!-- End Google Tag Manager (noscript) -->";

    if (jQuery('script[src="https://www.googletagmanager.com/gtm.js?id=GTM-XXXXXX"]').length === 0) {
        jQuery('head').prepend(gtmHeadCode);
        jQuery('body').prepend(gtmBodyCode);
    }
}
}());

这很好。 gtmHeadCode将附加脚本标签并执行js,在其中添加必要的google标记管理器的其他标头标签。

我决定放弃这一点,因为某些网站没有jQuery,并转而使用看起来像这样的纯js方法:      (window.addEventListener('load',function(){

    var gtmHeadCode = "<!-- Google Tag Manager -->" +
        "(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':" +
        "new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0]," +
        "j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=" +
        "'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);" +
        "})(window,document,'script','dataLayer','GTM-XXXXXXX');" +
        "<!-- End Google Tag Manager -->";

    var gtmBodyCode = "<!-- Google Tag Manager (noscript) -->" +
        "<iframe src='https://www.googletagmanager.com/ns.html?id=GTM-XXXXXXX'" +
        "height='0' width='0' style='display:none;visibility:hidden'></iframe>" +
        "<!-- End Google Tag Manager (noscript) -->";

if (document.querySelectorAll('[src="https://www.googletagmanager.com/gtm.js?id=GTM-XXXXXXX"]').length == 0) {
    var headTag = document.createElement('script');
    var bodyTag = document.createElement('noscript');
    headTag.setAttribute('type', 'text/javascript'); 

    headTag.innerHTML += gtmHeadCode;
    bodyTag.innerHTML += gtmBodyCode;
    document.head.insertBefore(headTag, document.head.firstChild);
    document.body.insertBefore(bodyTag, document.body.firstChild);
}
})); 

我在这里遇到的问题是原始script标记附加到DOM头,但是js似乎没有运行?为什么在附加jQuery前缀后可以正常工作,但在JS中insertBefore上却不能正常工作?

0 个答案:

没有答案