librewolf
librewolf

Reputation: 464

What do I replace document.write with when using asynchronous loading of javascript?

Story: I'm learning javascript and also about how alanytics and tracking systems work. I have read and investigated Google Analytics tracking code + their new & old documentation. But when I tried to replicate the process, I couldn't get through one specific part.

My problem + context I'm using a javascript code, which adds dynamically a new javascript code to the page. From what I understood, using this method:

<script type="text/javascript">
var hh = document.createElement('script');
hh.type = 'text/javascript';
hh.async = true;
hh.src = 'MY_EXTERNAL_JS.js';
var s = document.GetElementsByTagName('script')[0];
s.parentNode.insertBefore(hh, s);
</script>

is better then writing the direct tag:

<script src="http://api.dvekotvy.cz/hh.js"></script>

Because this way, the browser doesn't wait for the external JS file to render other content on the main page (correct me, if I'm wrong, but both dynamically written JS AND "async" attribute causes this).

The problem I'm facing is, that the JS file I'm requesting from external server, besides doing the cookies reading and navigator collecting, also uses document.write at the end to inject an img tag into the main page with all the collected data written as GET parameters and sent to the database by requesting this image. (At the server side, I use a PHP file to procces the data and return an 1x1 transparent pixel, as Google does).

The key question: What are my option to inject this tracking image with all its paraments from the external file, while keeping the JS request for this file asynchronous ?

Thanks for your help & ideas AR

Upvotes: 1

Views: 110

Answers (1)

Mat&#237;as Fidemraizer
Mat&#237;as Fidemraizer

Reputation: 64943

Easy: don't use document.write, use DOM (Document Object Model):

var img = document.createElement("img");
img.src = "http://";
// and so on
// Append your image wherever you want using appendChild
document.body.appendChild(img);

Upvotes: 1

Related Questions