views:

163

answers:

1

I have an app where generated HTML pages specify a single JavaScript file:

<script language="JavaScript" src="/global.js"></script>

In global.js is the following code, to load a single user-defined user.js file:

var UserJsFile = document.createElement("script");
UserJsFile.type = "text/javascript";
UserJsFile.src = "/user.js";
document.getElementsByTagName("head")[0].appendChild(UserJsFile);

// Add default onLoad handler
window.onload = global_onLoad;

// Global onLoad function
function global_onLoad(){
    submitdisabled = false;
    user_onLoad();
    document.forms[0].onsubmit = global_onSubmit;
}

and in user.js is similar code to allow the user to specify multiple user-defined JS files:

// Define all user-defined JavaScript sub-files
var UserJsFiles = [];
UserJsFiles[0] = "install.js";
UserJsFiles[1] = "complex.js";
UserJsFiles[2] = "gravis.js";
UserJsFiles[3] = "locator.js";
UserJsFiles[4] = "locator_x.js";

// Load all the user-defined JavaScript sub-files
for (i=0; i<UserJsFiles.length; i++) {
    var UserJsFile = document.createElement("script");
    UserJsFile.type = "text/javascript";
    UserJsFile.src = UserJsFiles[i];
    document.getElementsByTagName("head")[0].appendChild(UserJsFile);
}
// Perform any user-defined onLoad functionality
function user_onLoad() {
    // user code goes here
    return;
}

The problem I'm getting is that once the code in global.js has run (to attach user.js), the page seems to think it's loaded (even if not all the user-defined JS files have been attached/loaded), so it runs global_onLoad(), which fails because it calls user_onLoad() which may call user-defined onLoad functions in some of the other files...

At least, that's what I think is happening...

Am I missing something - is the attaching of each user-defined JS file as a DOM element happening asynchronously?

Note that my users can't use JQuery or any other JS framework, so if I do have a problem, I need to figure it out using simple JS...

A: 

Looks like this question has been asked and answered: http://stackoverflow.com/questions/774752/dynamic-script-loading-synchronization

roryhewitt
Actually, maybe not - the code in that post doesn't seem to work for me. More coffee required.
roryhewitt
The approach is correct. You may not be able to do a straight cut-and-paste.
Sean Hogan
OK, I'll take another crack at it. Thanks.
roryhewitt