可以覆盖 document.write 方法。因此,您可以缓冲发送到 document.write 的字符串,并将缓冲区输出到您喜欢的任何位置。但是,如果处理不当,将脚本从同步更改为异步可能会导致错误。这是一个例子:
简化的 document.write 替换
(function() {
// WARNING: This is just a simplified example
// to illustrate a problem.
// Do NOT use this code!
var buffer = [];
document.write = function(str) {
// Every time document.write is called push
// the data into buffer. document.write can
// be called from anywhere, so we also need
// a mechanism for multiple positions if
// that's needed.
buffer.push(str);
};
function flushBuffer() {
// Join everything in the buffer to one string and put
// inside the element we want the output.
var output = buffer.join('');
document.getElementById("ad-position-1").innerHTML = output;
}
// Inject the thid-party script dynamically and
// call flushBuffer when the script is loaded
// (and executed).
var script = document.createElement("script");
script.onload = flushBuffer;
script.src = "http://someadserver.com/example.js";
})();
http://someadserver.com/example.js的内容
var flashAdObject = "<object>...</object>";
document.write("<div id='example'></div>");
// Since we buffer the data the getElementById will fail
var example = document.getElementById("example");
example.innerHTML = flashAdObject; // ReferenceError: example is not defined
我已经记录了我在编写和使用 document.write 替换时遇到的不同问题:https ://github.com/gregersrygg/crapLoader/wiki/What-to-think-about-when-replacing-document.write
但是使用 document.write 替换的危险是所有可能出现的未知问题。有些甚至无法绕过。
document.write("<scr"+"ipt src='http://someadserver.com/adLib.js'></scr"+"ipt>");
adLib.doSomething(); // ReferenceError: adLib is not defined
幸运的是,我没有在野外遇到上述问题,但这并不能保证它不会发生;)
还想试试吗?试试crapLoader(我的)或writeCapture:
您还应该检查友好的 iframes。基本上,它会创建一个同域 iframe 并在那里加载所有内容,而不是在您的文档中。不幸的是,我还没有找到任何好的库来处理这个问题。