在<script>标记位置</script>处插入元素

时间:2010-05-07 15:14:00

标签: javascript embed

当网站为您提供一些JavaScript,您将其粘贴到网页中以在该位置插入内容时,脚本如何确定其在DOM中的当前位置?不使用document.write?

谢谢,

尼克

3 个答案:

答案 0 :(得分:5)

在脚本包含时,可以确定页面中的最后一个<script>将是当前的一个;页面的其余部分尚未解析。所以:

<script type="text/javascript">
    var scripts= document.getElementsByTagName('script');
    var this_script= scripts[scripts.length-1];

    // Something that happens later...
    //
    setTimeout(function() {
        var div= document.createElement('div');
        div.appendChild(document.createTextNode('Hello!'));
        this_script.parentNode.insertBefore(div, this_script);
    }, 5000);
</script>

只要脚本标记不使用defer或HTML5的async,就会成立。

答案 1 :(得分:0)

我不明白为什么这些脚本会关心它们在DOM中的位置,但我想可以确定。也许使用document.scripts之类的东西来开始搜索。

答案 2 :(得分:0)

我自己在寻找答案,我的情况是“创建一个动态src并将其添加到固定位置的脚本元素中”。

<script>Other code</script>
//Add my dynamically calculated script right here

我用过这样的东西

<script>document.write('<script src="myJs.js?v=' + Math.floor(Math.random() * 100) + '"\><\/script>');</script>

这是可行的,但是灯塔审核表明这是一种不好的做法。为了提高性能得分,我必须删除在多个地方使用的document.write。 我在下面编写了函数,并在需要添加此类脚本的地方调用它:

<script type="text/javascript">
    function insertScriptHere(src){
        var script = document.createElement('script');
        script.setAttribute("src", src + Math.floor(Math.random() * 100));
        document.currentScript.insertAdjacentElement('afterEnd', script);
    }
</script>
....
<script>insertScriptHere("myJs.js?v=");</script>

现在这可以正常工作了,并且审计报告中不再存在“避免使用document.write()”标记。