Issue using Google Analytics with Require.js

后端 未结 5 1366
说谎
说谎 2021-02-04 16:07

I\'m using require.js (http://requirejs.org/) for a number of functions on my site and so far it seems to be working well. I\'ve run into an issue when trying to include Google

5条回答
  •  天涯浪人
    2021-02-04 16:39

    None of the other answers worked for me, but I managed to figure out something that does work, after reading the Google Analytics documentation.

    in your main app.js

    requirejs.config({
        paths: {
            ga: '//www.google-analytics.com/analytics'
        }
    });
    
    requirejs(['analytics'], function () {
        ...
    });
    

    in its own file analytics.js:

    define(['ga'], function () {
        window.ga('create', 'UA-XXXXXX-1');
        window.ga('send', 'pageview');
    });
    

    This works because requirejs guarantees that by the time the function executes, analytics.js will have finished loading. This means that the window.ga function is ready to accept commands.

提交回复
热议问题