gpt4 book ai didi

javascript - 如何根据条件加载外部 JavaScript

转载 作者:行者123 更新时间:2023-12-05 00:28:13 25 4
gpt4 key购买 nike

问题是如何重写静态 HTML 脚本嵌入:

<script async id="__script__id__"
type="text/javascript"
src="//abc.xyz.com/js/script.js">
</script>
嵌入到程序化嵌入中,该嵌入仅允许在特定条件下加载脚本。
赏金设置为描述静态/编程嵌入如何彼此不同,特别是:
  • 解释 JS 规范如何处理以编程方式添加的脚本 - 当它们被加载和执行时 - 具有权威引用。
  • 解释将脚本嵌入从 HTML 内联转换为程序化如何影响浏览器优化(众所周知,浏览器会扫描带有 src 属性的 HTML 脚本标签并预加载它们)和权威引用。
  • 最佳答案

    如果您已经知道如何检测您的标准,那么加载另一个脚本如下所示:

    <head>
    <!-- the usual head stuff goes here -->
    <script>
    // replace `criteria` with your actual criteria
    if(criteria) {
    const script = document.createElement('script');
    script.id = '__script__id__';
    script.type = 'text/javascript';
    script.async = true;
    script.src = '//abc.xyz.com/js/script.js';
    document.head.append(script);
    }
    </script>
    <!-- remaining scripts go here -->
    <!-- injected script will end up here -->
    </head>
    检查条件,创建元素,设置其属性,将其添加到文档中。

    我尝试寻找有关此机制的详细信息。我能找到的最好的是来自 MDN 关于脚本元素 async and defer properties 的主题:

    The exact processing details for these attributes are complex, involving many different aspects of HTML, and therefore are scattered throughout the specification. These algorithms describe the core ideas, but they rely on the parsing rules for <script> start and end tags in HTML, in foreign content, and in XML; the rules for the document.write() method; the handling of scripting; and so on.


    不幸的是,我对 W3 的各种 HTML 规范没有必要的熟悉程度来将其转换为简单的英语,而且看起来需要相当长的时间才能变得熟悉。

    关于javascript - 如何根据条件加载外部 JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69685735/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com