tarling
tarling

Reputation: 1957

Deferring dynamically added Javascript

I need to load some Javascript dynamically after the page has loaded.

Something like this:

file2.js has a dependency on file1.js - it adds properties to an object defined in file1.js

The problem is that file2.js is loading first (because it is smaller), and is immediately throwing an error because its dependency doesn't exist.

Is there a way for me to defer evaluation/execution of these new scripts until they have all loaded. (There is actually more than two scripts)

If I were to just embed these scripts in a page normally in authored HTML, then it seems that the browser loads all scripts, then evaluates them. But it is behaving differently because I'm adding script elements on the fly.

Thanks

Upvotes: 5

Views: 317

Answers (3)

Category6
Category6

Reputation: 546

Two suggestions for you:

  1. Have a look at http://requirejs.org/ It solves this problem, among others.
  2. Or, roll your own simple js loader function. It would be a function that uses ajax to load a script and then calls a callback when it's done. Call this loader function in a nested way so that you load your scripts in the right order.

Upvotes: 1

Joris Lindhout
Joris Lindhout

Reputation: 205

Can't you wrap the contents of the files in functions and call them after everything has loaded?

Upvotes: 1

David Souther
David Souther

Reputation: 8184

There's a library called RequireJS that handles exactly this situation, and handles every situation you never realized were problems - http://requirejs.org/docs/start.html

Upvotes: 4

Related Questions