TerrorBight TerrorBight - 2 months ago 12
Javascript Question

Wait until a script is downloaded and executed and wait for DOM to be loaded

I have some Javascript that I need to run conditionally - it is not in a requirejs form. Also the script exists within the same server/domain as the requesting page (which contains the ajax call below)

Is there a definitive way to wait until an ajax get request to a Javascript file is downloaded and executed (all complete) as well as making sure the DOM is fully loaded. As well exception handling to accommodate when the download and/or the Javascript within fails.

I've seen many pages all with quite different solutions using (sync/async, when/done/deferred [http://www.bennadel.com/blog/2124-using-deferred-objects-as-an-asynchronous-script-loader-in-jquery-1-5.htm], labjs, etc) - but do these truly wait until the javascript code has completed execution ?

The following is what I've have but I'm not sure of the 'eval' solution and it doesn't check if the DOM is fully loaded (note that I've marked the dataType as 'text' so that it doesn't automatically execute as this is looked after by the eval)

var myScriptFileRequest = $.ajax({
url: '...myScriptFile.js',
dataType: "text",
cache: false,
async: true
myScriptFileRequest.fail(function (jqXHR, textStatus) {
document.getElementById(divId).innerHTML = "Error on if get:" + jqXHR.status + ":" + jqXHR.statusText + ":" + textStatus;
myScriptFileRequest.done(function (msg) {


Can be achieved fairly simply by placing the dependent code within the 'done' event (I thought there may be an event that may achieved the same thing)