0

I'm working on a project where I've had to greatly widgetize my code. As such, I'm loading 5 pages of JS dynamically into the DOM. The problem I'm having though is that I don't have a way to check and wait for these scripts to be loaded. If it takes them a second to get pushed up into the DOM, then my script tries to run, but fails when it calls on them.

Here's an example of how I'm embedding my scripts.

var script_tag2 = document.createElement('script');
script_tag2.setAttribute("type","text/javascript");
script_tag2.setAttribute("src","http://www.freeptools.com/mapster/js/three.min.js");
(document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag2);

This inserts it into the DOM, but I dont' have a way to pause my code until it's done. Has anyone run into this before? I'm trying to come up with a best practices for this, but coming up short.

4
  • jquery's getScript allows a callback to be called when the script is loaded (the idea behind I think is the onload event of the script dom element) Commented Feb 19, 2015 at 18:10
  • 5
    If it is tagged jQuery, why don't you use getScript? Commented Feb 19, 2015 at 18:10
  • $(document).load(function() {...}); should work... Commented Feb 19, 2015 at 18:11
  • 1
    I'd suggest to take a look on require.js ( requirejs.org ) and approaches used by Twitter Flight Framework ( flightjs.github.io ) . Commented Feb 19, 2015 at 18:13

1 Answer 1

1

Use jQuery.getScript

jQuery.getScript("http://www.freeptools.com/mapster/js/three.min.js")
    .done(function() {
        /* yay, all good, do something */
    })
    .fail(function() {
        /* boo, fall back to something else */
});
Sign up to request clarification or add additional context in comments.

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.