代码之家  ›  专栏  ›  技术社区  ›  mjallday

从javascript脚本重定向document.write

  •  2
  • mjallday  · 技术社区  · 16 年前

    我们希望在我们的网站上提供广告,但我们正在与之谈判的ads服务器在为我们提供足够快的广告方面存在问题。

    在我看来,问题是我们应该包括 <script src="http://advertiserurl/myadvertkey"></script> 在我们想要显示广告的地方,它将下载一个脚本并使用document.write插入一些html。

    是否有方法从document.write调用获取输出,并在页面加载后将其写入?

    基本上我想这样做:

    <html>
    <body>
    
        <script>
    function onLoad() {
        var urlToGetContentFrom = 'http://advertiserurl/myadvertkey';
    
        //  download js from above url somehow
    
        var advertHtml = // do something awesome to interprete document.write output
        $('someElement').innerHTML = advertHtml;
    }
        </script>
    
    </body>
    </html>
    

    或者任何类似的东西,让我得到文件的输出并显示它。

    4 回复  |  直到 16 年前
        1
  •  6
  •   Greg    16 年前

    如果我理解正确,您希望捕获文档。请写入变量,而不是将其写入文档。实际上,您可以这样做:

    var advertHtml = '';
    var oldWrite = document.write;
    
    document.write = function(str)
    {
        advertHtml += str;
    }
    
    // Ad code here
    
    // Put back the old function
    document.write = oldWrite;
    
    // Later...
    ...innerHTML = advertHtml;
    

    不过,您仍然可以加载脚本文件。

        2
  •  3
  •   Anonymous    16 年前

    要将主页加载与广告加载分离,您可以将广告放在iframe中自己的页面中,或者类似地,使用AJAX下载脚本文件,并在它关闭时执行它。如果由于引用URI或其他原因,前者不足以满足需要,那么后者会给您一些灵活性:您可以使用字符串替换将“document.write”重写为其他内容,或者临时替换为“document.write=custom_function;”。

        3
  •  1
  •   Eric Bréchemier    15 年前

    你可能对这件事感兴趣 the Javascript library I developed 允许使用document.write加载第三方脚本 之后 window.onload。在内部,该库重写document.write,动态附加DOM元素,运行任何包含的脚本,这些脚本也可能使用document.write。

    a demo, in which I load 3 Google Ads, an Amazon widget as well as Google Analytics dynamically .

        4
  •  0
  •   Chad Grant    16 年前

    由于同源策略,您在跨域时会遇到一些安全问题。如果您有权更改广告内容/服务,我会调查JSONP

    http://docs.jquery.com/Ajax/jQuery.getJSON#urldatacallback