将document.write异步更改为某些内容?

时间:2015-07-28 06:39:12

标签: javascript html

我试图关闭一些使用document.write的旧HTML,以防止在script.js无法立即加载时远程网站挂起。我可以访问script.js进行更改。

我的示例代码:

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

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

script.js输出示例。

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

我如何异步加载上面的代码?

更新

我发现了一段代码,我相信它会成功。

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

我只是不明白要放在script.js中的内容,以便在上面的输出示例中使用上面的代码片段。 script.js应该在上面的代码片段上有什么用?

1 个答案:

答案 0 :(得分: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/