Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
421 views
in Technique[技术] by (71.8m points)

javascript - Trigger $document.ready (so AJAX code I can't modify is executed)

My requirements are the following:

  • I've got a rich webpage that at a certain moment loads a bunch of HTML in a div, via AJAX.
  • The HTML I retrieve does have javascript (<script>...</script>)
  • The retrieved javascript contains $('document').ready( ... ) parts
  • I can not modify the retrieved javascript; it comes from an external lib
  • I've got a javascript function that is called when the AJAX is loaded. I'm trying to "trick it" into executing by doing:

    function AjaxLoaded() {
      $('document').trigger('ready');
    }
    

That doesn't cut it, I'm afraid.

I've seen several responses on Stack Overflow that "evade" this question by changing the code that is returned on the AJAX (make it a function and call it after loading, or just remove the $(document).ready()). I need to stress out that I can't change the retrieved code on this case.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Afer some research i created a way to get it to work.

here is my test that shows it working: http://www.antiyes.com/test/test2.php

here is the relevant code:

<script>
    // easy copy of an array
    Array.prototype.copy = function() {
        return [].concat(this);
    };

    // this function is added to jQuery, it allows access to the readylist
    // it works for jQuery 1.3.2, it might break on future versions
    $.getReadyList = function() {
        if(this.readyList != null)
            this.myreadylist =  this.readyList.copy();      
        return this.myreadylist;
    };

    $(document).ready(function() {
        alert("blah");
    });

</script>

<script>

    // this should be added last so it gets all the ready event
    $(document).ready(function() {
        readylist = $.getReadyList();
    });

</script>

then in the body I have:

<input type="button" onclick="$(readylist).each(function(){this();});" value="trigger ready" />

basically what i did was add a function to jQuery that copies the readyList before it's cleared out, then it will be available to be used by you.

it looks like the code below doesnt work:

function AjaxLoaded() {
    $(document).trigger('ready');
}

drop the quotes around document.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...