javascriptbingtracking-pixel

RefenceError: UET is not defined


I'm struggling to understand why this javascript error keeps popping up on my website and I can't reproduce it. I've followed the bing documentation to install their tracking pixel so I have this in my header :

  <script>
    (function(w,d,t,r,u){var f,n,i;w[u]=w[u]||[],f=function(){
      var o={ti:"xxxxxxxx"};o.q=w[u],w[u]=new UET(o),
              w[u].push("pageLoad")},n=d.createElement(t),n.src=r, n.async=1,
            n.onload=n.onreadystatechange=function(){var s=this.readyState;
              s&&s!=="loaded"&&s!=="complete"||(f(),n.onload=n.onreadystatechange=null)},
            i=d.getElementsByTagName(t)[0],i.parentNode.insertBefore(n,i)})
    (window,document,"script","//bat.bing.com/bat.js","uetq");
  </script>

However in some browsers, the UET variable in this code, which is loaded by the url given as the r variable, seems to not be defined while it's only called when the url is loaded...

If anybody can make sense of it before I reach out to bing, I'll be very thankful!


Solution

  • Building on the accepted answer, I believe there might a way to prevent these errors.

    Do you see the bit that says w[u]=new UET(o) in the script? We know that w means window there. And UET is an object created on the global scope (that is, on the global window object), thus it's existence can be tested with window.UET (try running window.UET on the console with and without loading the script, you'll see the former case returns undefined and latter case returns a function function UET(o) {...}. So, technically, you can alter the script putting a conditional there, like the following:

    if(w.UET){w[u]=new w.UET(o)}
    

    Here's my attempt to deconstruct the relatively cryptic looking <script> to a more readable function call for better visibility of what's happening there (this may also come handy if you're using it in an SPA like I do):

    function initMicrosoftUET(
      w,
      d,
      t = "script",
      r = "//bat.bing.com/bat.js",
      u = "uetq"
    ) {
      var f, n, i;
      w[u] = w[u] || [];
    
      f = function () {
        var o = { ti: "xxxxxxxx" };
        o.q = w[u];
        if (w.UET) w[u] = new w.UET(o) || [];
        w[u].push("pageLoad");
      }
    
      n = d.createElement(t);
      n.src = r;
      n.async = 1;
      n.onload = n.onreadystatechange = function () {
        var s = this.readyState;
    
        (s && s !== "loaded" && s !== "complete") || f();
    
        n.onload = n.onreadystatechange = null;
      }
    
      i = d.getElementsByTagName(t)[0];
      i.parentNode.insertBefore(n, i);
    };
    
    initMicrosoftUET(window, document);