Highlighted

The document object in a DOMReady Extension

sujani_koya
Regular Visitor
sujani_koya

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

2 REPLIES 2

The document object in a DOMReady Extension

UnknownJ
Occasional Contributor
UnknownJ Occasional Contributor

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).

The document object in a DOMReady Extension

powem
Visitor
powem

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