Search code examples
javascriptxamluno-platform

How to add Google Analytics Scripts to Uno WebAssembly


I am trying to add a google tag manager script to the Wasm project. To achieve this I have created a new script file localscript.js inside WasmScripts folder. This is how that file looks like

(function () {
    const head = document.getElementsByTagName("head")[0];

    var myScript = document.createElement('script');

    myScript.setAttribute('src', 'https://www.googletagmanager.com/gtag/js?id=UA-1234567-7');

    head.appendChild(myScript);
})();
window.dataLayer = window.dataLayer || [];
function gtag() { dataLayer.push(arguments); }
gtag('js', new Date());

gtag('config', 'UA-1234567-7');

And then I embedded this script to wasm.csproj file like this

  <ItemGroup>
      <EmbeddedResource Include="WasmCSS\Fonts.css" />
      <EmbeddedResource Include="WasmScripts\AppManifest.js" />
      <EmbeddedResource Include="WasmScripts\localscript.js" />
  </ItemGroup>

All looks good to me, But when I run this, localscript.js loads before googletagmanager. How can I solve this issue so that googletagmanager comes first and supporting code comes after that?


Solution

  • You can use the Uno.Wasm.Bootstrap provided require.js:

    require(
        ["https://www.googletagmanager.com/gtag/js?id=UA-1234567-7"],
        () => {
            window.dataLayer = window.dataLayer || [];
            function gtag() { dataLayer.push(arguments); }
            gtag('js', new Date());
    
            gtag('config', 'UA-1234567-7');
        }
    );
    

    This will make the code in the arrow function execute once the script has been downloaded.