在< script>处插入元素标签位置 [英] Insert elements at <script> tag position

查看:51
本文介绍了在< script>处插入元素标签位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

When sites give you some JavaScript that you paste into a web page to have content inserted at that position, how does the script determine its current position in the DOM? Without using document.write?

谢谢

尼克

推荐答案

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

At script inclusion time, it's certain that the last <script> in the page will be the current one; the rest of the page hasn't been parsed yet. So:

<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>

只要script标记不使用 defer 或HTML5的 async ,这都是正确的.

This holds true as long as the script tag doesn't use defer, or HTML5's async.

这篇关于在&lt; script&gt;处插入元素标签位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆