Change document.write in sync with something async?

I am trying to disable the old HTML it uses document.write

to prevent the remote website script.js

from loading immediately. 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>

      

Sample output script.js

.

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

How can I make the above code load asynchronously?

Update:

I found a piece 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

so that the above code snippet works with my previous example. What should be in script.js for the above code snippet to work?

+3


source to share


1 answer


I'm not really sure what I'm 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's contribution)

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

      

Update: (place at the beginning of the page)



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

Update: (location at current script position)

 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/

0


source







All Articles