简体   繁体   English

多次调用对象

[英]Calling object more than once

Hello I have code which replaces document.write , makes a buffer and than pushes buffer into the document: 您好我有代码替换document.write ,生成一个缓冲区,然后将缓冲区推送到文档中:

  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. 第一个init不会工作。 window.buffer will be empty. window.buffer将为空。 Where is my mistake? 我的错误在哪里?

PS another problem: I tried to replace window.onload with jQuery method $(window).load() but it fires twice. PS另一个问题:我试图用jQuery方法$(window).load()替换window.onload ,但它会触发两次。 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. 基本上,你只有一个缓冲区: window.buffer ,如果你调用init()两次,window.buffer将被第二次调用操纵,而第一次调用可能无法完成。 I'd recommend you use a seperate buffer for every init(). 我建议你为每个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. window.onload只会执行你最后分配给它的方法,而$(window).load()维护一个链,你可以init()两次,然后链中有两个方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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