0

I'm loading a JavaScript file on the fly. The response from the request to load this file has JavaScript in it, which I would expect to execute, but it doesn't.

http://jsfiddle.net/mXPXE/

This does not work (the remote script's JS does not execute):

var body = document.getElementsByTagName("body")[0];         
var newScript = document.createElement('script');
newScript.type = 'text/javascript';
newScript.src = 'https://pixel.adbuyer.com/conversion';
body.appendChild(newScript);

Whereas, this does work (the script's JS does execute):

var SWJsHost = (("https:" == document.location.protocol) ? "https://" : "http://");
document.write(unescape("%3Cscript src='" + SWJsHost + "pixel.adbuyer.com/conversion' type='text/javascript'%3E%3C/script%3E"));

What am I missing here? Why doesn't this work in the first case?

matthewpavkov
  • 2,918
  • 4
  • 21
  • 37
  • @apsillers Ok, but I have the same issue outside of jsfiddle. I'm testing on my own server. – matthewpavkov Dec 06 '13 at 16:19
  • Possible duplicate of [async loading javascript with document.write](http://stackoverflow.com/questions/13003644/async-loading-javascript-with-document-write) (that question sets `script.async = true`, but that's true by default for dynamically added scripts) – apsillers Dec 06 '13 at 16:32
  • In short, the script *does* load and run, but the `document.write` instructions (which make up the entire script) do not operate in asynchronous code. The solution here is to either 1) load the script synchronously, 2) rewrite the code, or 3) temporarily overwrite `document.write` to do something else (like examine the HTML strings and insert DOM objects using non-`document.write` methods). – apsillers Dec 06 '13 at 16:34
  • @apsillers Ok, that makes a bit more sense. I cannot use the second method to load the script, due to a mozilla bug. Any suggestions? – matthewpavkov Dec 06 '13 at 16:36
  • For an example on how to do my super-hacky third suggestion, see http://stackoverflow.com/questions/20004761/cant-load-script-as-plain-text-with-ajax/20005862#20005862 (but move the `delete document.write` somewhere else, to run after you've done all three calls) – apsillers Dec 06 '13 at 16:38
  • @apsillers Ah, that's pretty awful, but I'll consider doing that. Thanks for the help. If you add this stuff to an answer, I'll mark it. – matthewpavkov Dec 06 '13 at 16:55

1 Answers1

0

Try this please enter link description here

Use head instead of body

var head = document.getElementsByTagName('head')[0];
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = "https://pixel.adbuyer.com/conversion";
    head.appendChild(script);
script.onload = function () {alert(1);}
Vahe Shadunts
  • 1,956
  • 14
  • 18