Reply
Highlighted
Regular Visitor
Posts: 49
Registered: ‎09-22-2015

The document object in a DOMReady Extension

[ Edited ]

Hi,  can we reference the document object in a DOM Ready scoped extension?  I tried to add a Floodlight tag to the Add to Cart button whose tracking code is in a DOM Ready Extension.   On clicking the button a blank page was turning up that had to be refreshed to go ahead with the purchase process.  There was a document.write line that could have caused a issue in the site. Thanks a lot

Reply
0 Kudos
Occasional Contributor
Posts: 120
Registered: ‎12-11-2015

Re: The document object in a DOMReady Extension

Hi @sujani_koya,

My understanding is that document.write can only be invoked while a page is being rendered and its content is effectively being composed by the rendering engine. So it suits synchronous injections of content in, for example, utag.sync.js.

However, it's not appropriate for tags that fire after the DOM content has been loaded - at that point, nodes should be injected into the completed DOM using the relevant methods, and using document.write will overwrite the entire page (usually leaving it blank).

Visitor
Posts: 7
Registered: ‎03-05-2018

Re: The document object in a DOMReady Extension

Hello,

The previous reply is correct. What happens is that your page reaches DOM Ready, and the document.write() is invoked, overwriting the entire page with its (invisible) content. 

You could do something like this.

var attr = {
   type: "text/javascript",
   src: "https://cdn.somewhere.com/my/tag.js"
};

function scriptWrite(attr){
  var head = document.getElementsByTagName("head")[0],
        script = document.createElement("script");
  Object.assign(script,attr);
  head.appendChild(script);
}

Of course, since this code will execute asynchronously, you may run into timing issues during execution from an event handler.  

"If it sounds good, it is good." - Duke Ellington
Reply
0 Kudos