开发者

Is there a way to intercept `document.write`?

开发者 https://www.devze.com 2023-02-06 08:12 出处:网络
I am trying to lazy load some adserver code... On the page I have this at the moment: <div class=\"ad\">

I am trying to lazy load some adserver code...

On the page I have this at the moment:

<div class="ad">
    <span>pos_1</span>
</div>

I then go through and pull out all of the ads that should be on the page, call their javascript include file and it gives me this lovely mess:

function do_ad(pos){
    switch(开发者_StackOverflow中文版pos){
        case 'pos_1':
            document.write('first ad text');
            document.write('first ad more text');
            //and so on for many many lines
            break;
        case 'pos_2':
            document.write('second ad text');
            document.write('second ad more text');
            //and so on for many many lines
            break;
    }
}

I then want to replace the span with the results of the document.write ad call.

Is there a way to get it to return the string that would have been written to the page?


I don't see why you can't overwrite the document.write function:

document.old_write = document.write;

document.write = function (str) {
    // lalala
};

See here: http://www.jsfiddle.net/N9hXy/


document.write = function(str) {
    window.buf += str;
}


The do_ad(pos) function must be called somewhere. Why not where the ad should be displayed?

<div class="ad">
    <script>do_ad("pos_1");</script>
</div>
0

精彩评论

暂无评论...
验证码 换一张
取 消