3 ms·
Warning: while the above async loading code works for Twitter, it won't work for any JavaScript containing calls to document.write() as they'll append the data
by jasondavies 16y ago
Warning: while the above async loading code works for Twitter, it won't work for any JavaScript containing calls to document.write() as they'll append the data to the end of the page depending on the browser (or even replace the whole page!)
All is not lost though, as you can patch document.write to do the right thing and write to an element's .innerHTML or equivalent. If you are a JavaScript API provider though, please take heed and don't use document.write(). I'm looking at you, PollDaddy!
- gawker 16y agoI've experienced this before and let me just say that it was hell to debug! TribalFusion seems to have done the same - using document.write() and document.writeline().
- rarestblog 16y agoYes, thank you, I've forgot to mention it. It will work for StatCounter and Twitter though.
- bemmu 16y agoHow would you handle waiting simultaneously on multiple scripts that all want to use document.write? I use some ad networks which want to call document.write to insert the ads. First I patch the document.write to a function that writes to the innerhtml for the first ad tag, then after that ad loads I change the function and start loading the next one. Obviously slower than doing it simultaneously. I suppose I could look at the contents of how the function is called to determine which ad it came from, but did you have some better idea?
- jasondavies 16y agoThat's a tricky one. I haven't tested this, but I think you should be able to listen for the 'load' event on each of the script elements that you inject, and patch document.write differently each time. Let me know how you get on! I plan on doing something like this soon for some of my sites that have AdSense (another document.write culprit).
- toolate 16y agoI just pushed up a class I've been using to do this to github. It's a little rough around the edges, but works in Firefox and IE. I've trialed with the AddThis. http://github.com/joshduck/Injector.js http://github.com/joshduck/Injector.js