动态加载JavaScript到Div [英] Loading JavaScript Into Div Dynamically

查看:92
本文介绍了动态加载JavaScript到Div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将JavaScript代码(我无法控制)从URL加载到div中。 JavaScript代码是一堆document.write()语句。一旦document.write()语句完成执行,我需要使用jQuery或JavaScript从div中提取结果文本,并将该文本用于其他内容。目前,我正在执行以下操作将JavaScript加载到div中:

I need to load JavaScript code (which I don't have control over) from a URL into a div. The JavaScript code is a bunch of document.write() statements. Once the document.write() statements finish executing, I need to extract the resulting text from the div using jQuery or JavaScript and use that text for something else. Currently, I am doing the following to load the JavaScript into the div:

    $('body').append('<div id="mydiv" style="display: none"></div>');
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = url;
    $('#mydiv').append(script);

我如何知道document.write语句何时完成执行并且我可以安全地提取文本div和使用它?或者,有更好的方法吗?

How would I know when the document.write statements have finished executing and I can safetly extract the text out of the div and use it? Or, is there a better way of doing this?

推荐答案

document.write()加载文档后将清除文档并开始新文档。你没有 document.write()进入一个已经存在的div,除非它是包含在该div中的内联javascript,并在文档加载/渲染时加载。

document.write() after your document is loaded will clear your document and start a new one. You don't document.write() into a div that already exists unless it's inline javascript that is included in that div and is loaded as your document loads/renders.

所以,这给你两个选择:

So, that leaves you two options:

1)你可以创建一个空的iframe并将JS加载到iframe并让它渲染到那个iframe中。如果您没有JS的合作,您可能需要轮询以查看渲染何时完成。如果你正确地创建了iframe,你可以设置一个监视器来查看iframe的加载时间。

1) You can create an empty iframe and load the JS into that iframe and let it render into that iframe. If you have no cooperation from the JS, you will likely have to poll to see when the rendering appears to be done. If you create the iframe properly, you may be able to set up a monitor to see when the iframe is loaded.

2)你可以在你的div中包含JS内联当你的页面加载时它会渲染到你的div中。这需要将div和脚本文件烘焙到您自己的页面HTML中,如下所示:

2) You can include the JS inline into your div and it will render into your div as your page is loaded. This would require baking the div and the script file into your own page HTML like this:

<div id="renderTarget">
<script src="xxx.js"></script>
</div>

如果你这样做,那么你会知道它是在你自己的文件是完成加载。

If you did it this way, then you would know that it was done rendering when your own document was done loading.

这篇关于动态加载JavaScript到Div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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