简体   繁体   中英

Jquery document ready on dynamically loaded HTML fires early

I am loading a dynamic content as follow:

$('#my-div').load('my.html');

Inside of my.html is a code like this

<html>
    <head>
    </head>
    <body>
        <script>
            $(function(){
                alert('should fire later');});
        </script>
    </body>
    <script>
        alert('should fire first!');
    </script>
</html>

Originally my.html was loaded inside an iframe and everthing was good.

However in order to refactor and modernize the code it was changed to use ajax load. However, now the order of execution is reversed, because technically the ready event has already fired on the parent page.

The problem with this is that there are dependencies that exist that requires the events to fire off in the correct order. I am also hesitant to move the script block higher up, as this code is overly reused and I have no idea what else would break. Although in smoke testing, moving the script block up works on the one page I was working on.

Is there a to use jquery ajax load and keep the originally intended order of script execution?

Try this:

<html>
    <head>
    </head>
    <body>
        <script>
            function later () {
                alert('should fire later');
            }
        </script>
    </body>
    <script>
        alert('should fire first!');
        later();
    </script>
</html>

What happens if you check the load state like this ?

<html>
    <head>
    </head>
    <body>
        <script>
            jQuery(window).load(function () {
        alert('page is loaded');
    });
        </script>
    </body>
</html>

However you can check the state of Ajax load by using this approach :

 $( document ).ajaxComplete(function( event,request, settings ) {
$( "#my-div" ).append( "<span>Request Complete.</span>" );
});

You can find useful information here : AjaxComplete()

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