如何让浏览器运行dom操作注入的javascript代码?

如何解决如何让浏览器运行dom操作注入的javascript代码?

我想提供一个其他页面可以包含的小 html 片段。

html 内容如下所示:

<div id="coolIncludable" style="display:none"> <!--be invisible until you are finished initializing -->
   <div>Cool stuff here</div>
   <div>More cool stuff and so on...</div>
</div>
<script src="http://somehwere/jquery.js"></script>
<script src="http://somewhere/something.js"></script>
<script>
    $(function(){$('#coolIncludable').show();});//<- actually contained in a script file,just for illustration
</script>

我打算使用此处详述的方法https://www.w3schools.com/howto/howto_html_include.asp 进行实际包含。假设页面看起来像这样:

<html>
    <head>
    </head>
    <body>
        <H1>Content before snippet</H1>
        <div id="registerWrapper" html-include="http://somehwere/snippet.html">
            No content loaded
        </div>
        <H1>Content after snippet</H1>
        <script type="text/javascript" src="http://somehwere/html-include.js"></script>
    </body>
</html>

html 代码段被加载并嵌入,但它附带的 javascript 永远不会被执行。有没有办法嵌入内容包括确保执行的脚本?

更新 我应该明确表示我不希望控制嵌入页面,所以我不能依赖它加载了 jQuery 或其他任何东西。因此,我避免在嵌入函数中使用 jQuery,并将自己限制在纯 Javascript 中。加载 jQuery 是代码片段末尾的标签要做的事情之一。

解决方法

由于您使用的是 jQuery,您可以使用它内置的 load() 方法来做您想做的事

类似于:

HTML

<div class="include" data-include="page2.html"></div>

JS

$('.include').each(function(){
     const $el = $(this),url = $el.data('include');
     $el.load(url)
});

然后确保新内容的脚本标记位于该内容下方。

Simple working demo

,

回想起来,我的错误非常明显:

$(function(){$('#coolIncludable').show();});是什么意思 做?它执行$('#coolIncludable').show();吗?不,它没有。它注册了一个回调,以便由 'load' 事件触发,该事件已经触发,并且不会再次触发。

另一方面,这确实是一个有争议的问题,因为代码甚至从未被执行过。

这是我学到的关于 javascript 动态加载的知识

直接注入脚本标签不起作用

  • 通过设置 element.innerHtml 注入的脚本标签被执行
<div id="snippet">
    ...
</div>
<!-- neither of these will be executed -->
<script type="text/javascript">alert("stuff");</script> 
<script type="text/javascript" src="http://somewhere/script.js"></script>

动态创建脚本标签确实有效

有效的是动态标记生成,如本文所述:JavaScript Madness: Dynamic Script Loading

var head= document.getElementsByTagName('head')[0];
var script= document.createElement('script');
script.type= 'text/javascript';
script.src= 'helper.js';
head.appendChild(script);
//At this point (or soon after) the code in helper.js will be executed

您可以在加载脚本中执行此操作。我的加载脚本如下所示:

function importJsFiles(){
    const scriptFiles = ["http://somewhere/jquery.js","http://somewhere/stuff.js","http://somewhere/bootstrapSnippet.js"];
    for (let i = 0; i< scriptFiles.length; i++){
        importJsFile(scriptFiles[i]);
    }
}

function includeSnippet(){
    //See https://www.w3schools.com/howto/howto_html_include.asp
    //We still have to do it without jQuery,//because at the time this executes the injected jquery.js 
    //hasn't run and we do not yet have jQuery available
}



importJsFiles();
//At this point,all script tags are created,but the scripts are NOT loaded yet
includeSnippet();
//At this point,the dom is in its final shape
bootstrapSnippet(); //<- This won't work,because the script tags injected by this code won't be evaluated until after this file/function/whatever returns

//bootstrapSnippet.js
function bootstrapSnippet(){
    alert("Snippet JS running")
    if (window.jQuery) {
            
            alert("JQuery is avaliable"); //<- This will fire,because the new script 
                            // tags are evaluated in order,and we put the
                            // jquery.js one before the bootstrapSnippet.js one
        }

        //So now we CAN do this:
        $('#coolIncludable').show(); 
}

bootstrapSnippet();

this post 中有更多有趣的想法和细节,我从中选择了上面的链接。我希望有一天我能抽出时间来探索它们。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?
Java在半透明框架/面板/组件上重新绘画。
Java“ Class.forName()”和“ Class.forName()。newInstance()”之间有什么区别?
在此环境中不提供编译器。也许是在JRE而不是JDK上运行?
Java用相同的方法在一个类中实现两个接口。哪种接口方法被覆盖?
Java 什么是Runtime.getRuntime()。totalMemory()和freeMemory()?
java.library.path中的java.lang.UnsatisfiedLinkError否*****。dll
JavaFX“位置是必需的。” 即使在同一包装中
Java 导入两个具有相同名称的类。怎么处理?
Java 是否应该在HttpServletResponse.getOutputStream()/。getWriter()上调用.close()?
Java RegEx元字符(。)和普通点?