许多网络广告提供商使用旧的 document.write 方法,在我的例子中是 AdTech。是否可以覆盖 document.write 方法以在 onload 事件之后延迟?
问问题
2258 次
4 回答
3
How about using either
- writecapture (https://github.com/iamnoah/writeCapture) an utility to assist the Ajax loading of HTML containing script tags that use document.write or
- PostsScribe (https://github.com/krux/postscribe/) which lets you deliver a synchronous ad asynchronously without modifying the ad code.
于 2013-10-01T14:37:33.680 回答
0
将所有脚本移动到页面底部(在 >/body< 之前),广告脚本绝对最后,并且根本不使用 domReady(如果在所有 HTML 元素之后放入脚本,则不需要它)会做同样的事情. 事实上,延迟 document.write 调用甚至可能毁掉整个页面,这取决于广告代码的可怕程度。
于 2010-09-01T16:54:33.280 回答
0
你可以输出一个
document.old_write=document.write;
window._bufferedText='';
document.write=function(text) {
window._bufferedText+=text;
}
//now let all the document.write go here
document.write('<h1>');
document.write('Hello World!');
document.write('</h1>');
//alert(window._bufferedText);
//end document.write methods
document.write=document.old_write;
document.write('<div id="deferred-write-placeholder"></div>');
window.onload=function() {
document.getElementById('deferred-write-placeholder').innerHTML=window._bufferedText;
delete window._bufferedText;
}
笔记:
document.write
您可以重写一些更复杂的东西来处理代码块的所有实例。- 你应该
window.onload
用你的 javascript 框架特定的 onload 处理程序替换。
于 2010-09-01T16:57:26.033 回答
0
您实际上可以通过拦截对 document.write 的调用以正确的方式支持脚本注入,如下所示。诀窍是创建一个“中间人”函数来检查 document.write 的输入,如果它是注入的脚本标签,则将其正确加载到 DOM 中:
document.writeText = document.write;
document.write = function(parameter) {
if (!parameter) return;
var scriptPattern = /<script.*?src=['|"](.*?)['|"]/;
if (scriptPattern.test(parameter)) {
var srcAttribute = scriptPattern.exec(parameter)[1];
var script = document.createElement('script');
script.src = srcAttribute;
document.head.appendChild(script);
}
else {
document.writeText(parameter);
}
};
显然,这可以进一步压缩,但为了清楚起见,包含了变量名称。如果您愿意,您可以在加载第三方库本身的脚本标签上使用 async 和 defer 来跟进,确保在此类更改后测试正确性。
于 2017-01-18T11:14:27.123 回答