JavaScript - 控制document.write的插入点 [英] JavaScript - controlling the insertion point for document.write

查看:101
本文介绍了JavaScript - 控制document.write的插入点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在DOM已经完全加载后创建一个运行第三方脚本的页面,其中包含 document.write

I would like to create a page that runs a 3rd party script that includes document.write after the DOM was already fully loaded.

我的页面不是XHTML。我的问题是document.write覆盖了我自己的页面。 (一旦加载了DOM就会这样做。)

My page is not XHTML. My problem is that the document.write is overwriting my own page. (which is what it does once the DOM was loaded).

我试图覆盖document.write函数(类似于 http://ejohn.org/blog/xhtml-documentwrite-and-adsense/ )但不是覆盖document.write包含部分标记的情况。

I tried overriding the document.write function (in a way similiar to http://ejohn.org/blog/xhtml-documentwrite-and-adsense/) but that doesn't cover cases where the document.write contains partial tags.

打破上述代码的一个例子是:

An example that would break the above code is:

document.write("<"+"div");
document.write(">"+"Done here<"+"/");
document.write("div>");

有没有办法通过JavaScript修改document.write插入点?有没有人知道如何做到这一点?

Is there some way to modify the document.write insertion point through JavaScript? Does anyone have a better idea how to do this?

推荐答案

如果您正在处理第三方脚本,只需更换文档即可。写入以捕获输出并将其粘贴在正确的位置是不够的,因为他们可以更改脚本然后您的网站会中断。

If you're dealing with 3rd party scripts, simply replacing document.write to capture the output and stick it in the right place isn't good enough, since they could change the script and then your site would break.

writeCapture.js 做你需要的(完全披露:我是作者)。它基本上重写了脚本标记,以便每个标记捕获它自己的 document.write 输出并将其放在正确的位置。用法(使用jQuery)类似于:

writeCapture.js does what you need (full disclosure: I'm the author). It basically rewrites the script tags so that each one captures it's own document.write output and puts it in the correct place. The usage (using jQuery) would be something like:

$(document.body).writeCapture().append('<script type="text/javascript" src="http://3rdparty.com/foo.js"></script>');

这里我假设您要追加到身体的末端。所有jQuery选择器和操作方法都可以与插件一起使用,因此您可以将它注入任何地方,无论您想要什么。如果这是一个问题,它也可以在没有jQuery的情况下使用。

Here I'm assuming that you want to append to the end of the body. All jQuery selectors and manipulation methods will work with the plugin, so you can inject it anywhere and however you want. It can also be used without jQuery, if that is a problem.

这篇关于JavaScript - 控制document.write的插入点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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