3

I'm trying to switch out some old HTML that uses document.write to prevent a remote website hanging if script.js doesn't load right away. I have access to script.js to change it.

My example code:

<script language="JavaScript"> 
var foo1 = "test 1";
var foo2 = "test 2";

document.write('<script src="script.js?id=' + foo1 + '&num=' + foo2 + '"><\/script>'); 
</script>

Example of script.js output.

document.write("<a href='http://example.com/file.php?id=123' title='title'>some data</a>")

How would I go about making my above code load asynchronously?

Update:

I found a snippet of code that I believe will do the trick.

<script>
    var script = document.createElement('script');
    script.src = "script.js";
    document.getElementsByTagName('head')[0].appendChild(script);
</script>

I just don't understand what to put in script.js to make the snippet of code above work with my output example earlier. What should be on script.js for the snippet of code above to work?

chillers
  • 1,447
  • 2
  • 15
  • 25

1 Answers1

0

I am not exactly sure what I are you trying to accomplish, but something like this in script.js might work:

document.getElementsByTagName('body')[0].innerHTML = "<a href=..>Something</a>";

Update: (+1 for Sam contribution)

document.getElementsByTagName('body')[0].innerHTML += "<a href=..>Something</a>";

Update: (place at beginning of the page)

document.getElementsByTagName('body')[0].innerHTML = "<a href=..>Something</a>" + document.getElementsByTagName('body')[0].innerHTML;

Update: (place at current position of script)

 var p = document.createElement("p");
    p.innerHTML = "aaa";

    var scripts = document.getElementsByTagName('script');
    var current = scripts[scripts.length - 1];

    current.parentNode.insertBefore(p, current);

http://jsfiddle.net/ekohfq5h/

sitnarf
  • 407
  • 2
  • 9
  • I tested it locally and it does load like I want it to. The problem is when I add just plane text in the HTML after it. It replaces that page with just "something" like it erases what is ever on the page and display "something " only. – chillers Jul 28 '15 at 22:22
  • Use … `innerHTML +=` … – sam Jul 28 '15 at 22:32
  • @sam I have now `document.getElementsByTagName('body')[0].innerHTML += "Something";` on `script.js` and it works but it places it after the testing text now on the HTML page. I have it for testing purposes on the HTML code I have the `` then some text words after it to make sure it loads in the correct spot. – chillers Jul 28 '15 at 22:38
  • @sitnarf I have no control where users place the code. So it will have to load where ever they place it on their page. On your 2nd update it works if there is text after it now in the correct location but if you put text in front of `` it places "something" in front of all the text. – chillers Jul 28 '15 at 22:46