views:

69

answers:

2

I made this method to load JavaScript functions dynamically. It does include the .js file, but when I call a method, the method says that it is undefined. The following two .js files are ajax_object.js and user_manager.js.

The alert outside the function is read and works, but the alert inside does not.

enter code here
//ajax_object.js
//Load a javascript library
 function loadJavascript( src, url ){

XMLHttpRequestObject=getXmlHttpRequestObject();

if( XMLHttpRequestObject){

    XMLHttpRequestObject.onreadystatechange = function()
    {
        if (XMLHttpRequestObject.readyState == 4 ){


            if (XMLHttpRequestObject.status == 200 || XMLHttpRequestObject.status == 304) {
                includeJavaScript( src, url, XMLHttpRequestObject.responseText );
            }
        }
    }

}

XMLHttpRequestObject.open('GET', url, true);
XMLHttpRequestObject.send(null);

  }//end LoadJavaScript

 //Add Library to header
function includeJavaScript(src, fileUrl, xmlObject)  { 
if ( ( xmlObject != null ) && ( !document.getElementById( src ) ) ){ 
    var documentHead = document.getElementsByTagName('HEAD').item(0);
    var includeScript = document.createElement( "script" );
    includeScript.language = "javascript";
    includeScript.type = "text/javascript";
    //includeScript.id = src;
    includeScript.src=fileUrl.concat(src);
    includeScript.defer = true;
    includeScript.text = xmlObject;
    documentHead.appendChild( includeScript );
} 
  } 

//user_manager.js
 //First alert is read
 alert("Outside User Manager");
  function selectUserManagerModuleType(){
XMLHttpRequestObject=getXmlHttpRequestObject();
//This doesn't work
    //throws selectUserManagerModuleType undefined
alert("Inside The User Manager");



    }
A: 

The problem came to an asychnrounous vs sychronous. The solution became very simple with JQuery.

function loadJavascript( src, url ){

    $.ajaxSetup({async: false});
    $.getScript(url.concat(src));
    $.ajaxSetup({async: true});

}
A: 

Your code is a bit odd, you are both giving the script block an src and a body, seemingly containing the same script.

I see two ways of doing this, either you simply add a script block to the header including an src, no ajax call needed for this (I have never seen this done before, so no guarantees as to what will happen). Or you load the script using an ajax call and eval the content returned, you got to beware about scope, otherwise you might end up having the downloaded script declaring stuff in the scope of the function that does the eval, but otherwise it is pice of cake.

If you replace the includeJavaScript call with:

eval("with(window){"+XMLHttpRequestObject.responseText+"}")

I don't see why it shouldn't work.

eBusiness