user1007132
user1007132

Reputation: 65

javascript callback context issue

Trying to make a simple widget. Steps:

1) Load jQuery if not already there 2) Callback a function

<html>
<head>
    <script type="text/javascript">
    function load(callback){
        console.log('load');
        if (typeof jQuery !== "function") {
            var js = document.createElement("script");
            var he = document.getElementsByTagName('head')[0];
            js.type = "text/javascript";
            js.src = "http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js";
            he.appendChild(js);
            js.addEventListener("load", function () {
                callback();
            });
        }
        else
            {
                callback();
            }
    }


    load(function(){
        chart();
    })


    function chart(){
        $('#chart').html("id : "+Math.random());
    }

    // alert('This alert breaks!');
    </script>
</head>
<body>
    <div id="chart"></div>
</body>
</html>

Code works without alert. Cant understand the context issue

Thanks

Upvotes: 0

Views: 97

Answers (2)

roland
roland

Reputation: 7775

Move your script block out of the head tag and place it at the end of the body right before </body>.

Upvotes: 0

Karl-Andr&#233; Gagnon
Karl-Andr&#233; Gagnon

Reputation: 33870

Alright, figured out the problem.

Your code is not inside a DOM ready handler.

It will work if the alert isnt there since the function call is asynchronous and the DOM is ready before the AJAX is complete.

but when the alert is there, it create a breakpoint in your code and the DOM will not complete until you click ok. The probleme is that the AJAX request isnt stopped. When you click ok, the AJAX will be finish and run the callback before the DOM is ready.

Upvotes: 4

Related Questions