0

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

3
  • Works for me in Chrome: jsfiddle.net/Zwa7Q Commented Jan 14, 2014 at 21:27
  • 1
    Just you are not waiting for DOM to be ready so $('#chart') could be empty object Commented Jan 14, 2014 at 21:29
  • @A.Wolff Cant thank you enough Commented Jan 14, 2014 at 21:33

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.