5

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

Something like this:

  • page loads

  • page adds script element with src = "file1.js"

  • page adds script element with src = "file2.js"

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

4

3 回答 3

4

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

于 2013-09-11T13:50:57.593 回答
1

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

于 2013-09-11T13:52:06.633 回答
1

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.
于 2013-09-11T13:55:44.603 回答