Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deferring dynamically added Javascript

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

like image 549
tarling Avatar asked Sep 11 '13 13:09

tarling


2 Answers

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

like image 163
David Souther Avatar answered Sep 30 '22 13:09

David Souther


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

like image 24
Joris Lindhout Avatar answered Sep 30 '22 13:09

Joris Lindhout