简体   繁体   中英

Calling object more than once

Hello I have code which replaces document.write , makes a buffer and than pushes buffer into the document:

  var lazyLoad = {

    url: '',
    block: '',
    buffer: '',

    init: function(url,block){
        that = this
        that.url = url;
        that.block = block;

        console.info(this.block)
        console.log(this.url)

        window.d = document
        window.onload = function(){
            that.work()
        }   
    },

    work: function(){
        that = this
        d.write = d.writeln = function(s){ 
                                    that.buffer += s
                                }
        d.open = d.close = function(){}
        s = d.createElement('script');       
        s.setAttribute('type','text/javascript');
        s.setAttribute('src',that.url);
        d.getElementById(that.block).appendChild(s)
        s.onload = function () {
            window.setTimeout(function() {

                console.warn(that.block + ' ' +that.buffer)
                d.getElementById(that.block).innerHTML += that.buffer;
                that.buffer = '';
            }, 0);
       }
    }
}

If I init it once:

lazyLoad.init(
        'http://test.com/test.js',              
         div1
)

But if I call it again with other parameters:

lazyLoad.init(
        'http://test2.com/test.js',             
         div2
)

First init wont work. window.buffer will be empty. Where is my mistake?

PS another problem: I tried to replace window.onload with jQuery method $(window).load() but it fires twice. How can I fix it?

basically, you have only one buffer: window.buffer , if you call the init() twice, the window.buffer will be manipulated by the second call, while the first call might not complete. I'd recommend you use a seperate buffer for every init(). which can essentially avoid this issue.

For your second question,

window.onload != $(window).load()

window.onload will only execute the method you last assign to it, while $(window).load() maintains a chain, you can init() twice, then there are two methods in the chain.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM