附加包含document.write的JS文件

时间:2016-06-28 20:11:47

标签: javascript jquery

我有一个JS脚本,.append()另一个脚本body以及它附加的内容:

<script type=\"text\/javascript\" src=\"https:\/\/website\/creative\/camref:[ref]\/creativeref:[ref]\"><\/script>

在此脚本中,它包含document.write(),我不能修改此文件。

它不会将脚本内部的内容写入网站,我该如何解决这个问题?异步工作(我知道异步承诺)?

1 个答案:

答案 0 :(得分:3)

您有三种选择:投放拥抱替换

自己提供剧本

如果您可以在自己的服务器上放置一些代码,则可以让代码获取远程脚本并在前端代码的路上进行修改。您的JavaScript代码将使用您自己网站上的URL而不是远程网站。处理此URL的服务器代码会获取远程脚本并执行文本替换,以使用与您的站点配合使用的其他代码更改脚本中的document.write()调用,例如:通过使用jQuery / DOM调用。然后它将此修改后的脚本作为自己的响应发送。

这可以很好地工作,但要注意远程脚本服务条款的潜在问题,以及可能的速率限制或更糟糕的情况,因为对远程服务器的所有请求现在都来自您的服务器而不是访问者& #39;浏览器。

拥抱document.write()

您从远程服务器加载的脚本假定它将在您的网页<script>中加载直接<body>标记。这是document.write()唯一可以正常工作的时间。如果在加载页面后从动态脚本调用document.write(),则会清除当前页面内容,如您所发现的那样。

因此,不是使用.append()加载远程脚本,而是按照预期的方式加载它,并在页面本身使用实际的<script>标记。然后,脚本的document.write()将在您加载页面时写入页面,而不会擦除页面的其余部分。

但是如果你需要将动态参数传递给脚本呢?假设您知道或可以在加载页面时计算这些参数,您可以在自己的脚本(内联或document.write()文件)中调用.js来编写加载远程脚本的脚本标记。这就像在HTML中内嵌远程<script>标记一样,除了您可以动态创建URL。

如果您需要将参数传递给以后不知道的脚本(例如,从用户输入到页面中),或者如果您不能将脚本加载到以后,则会赢得&#39;工作。

示例:

<!-- This goes inside the <body> tag where you want the remote script. -->
<script>
    var value = 'test';
    document.write(
        '<script src="https://example.com/script?foobar=', value,
        '"><\/script>'
    );
</script>
<!-- The remote script's document.write() output will go here. -->

替换document.write()

提供您自己的document.write()实现,它使用jQuery / DOM来获取本已编写的文本,并将其动态插入到您想要的位置。

示例:

// Do this in your JavaScript code immediately before using .append()
// or the like to load the remote script.
document.write = function() {
    // document.write can take multiple arguments, so concatenate them.
    var text = Array.prototype.slice.call( arguments ).join( '' );
    // Now text is what would have been written by document.write().
    // Use a DOM/jQuery/etc. call here to insert it into your page.
};
// Here is where you will load the remote script

现在,当远程脚本调用document.write()时,它将真正调用您的函数,因此您可以根据需要处理它。

不会像这样替换document.write()可能会破坏其他有效的代码并合法地使用它吗?不,因为任何此类工作代码都会在页面加载期间运行,否则它将被破坏。在页面完全加载之后,您才能更换该功能。

主要风险是,如果您正在加载的其他代码也使用同样的技巧。他们的document.write()替换你的{{1}}可以相互踩踏。