Click to See Complete Forum and Search --> : Include Javascript dynamically?


Krumelur76
June 10th, 2009, 07:32 AM
Hi!

I'm working on an AJAX app. My XmlHttpRequest responses contain HTML which replaces the client's current HTML but the response also contains a bit of Javascript which constructs new objects:


var oControl = new MenuControl();
oControl.RegisterDiv("elMenuDiv");


MenuControl is defined in MenuControl.js. There are a couple of other JS includes. I don't want to include all of them (<script src="MenuControl.js"></script><script src="SomethingElse.js"></script>) in the beginning because maybe only one (like "MenuControl") will ever be used.

So if the the server's response requires MenuControl.js to be include, I want to include it. If then in the next response, "SomethingElse.js" is required, I want to include that.

What I have tried so far:


var elScript = document.createElement("script");
elScript.setAttribute("language", "JavaScript");
elScript.setAttribute("type", "text/javascript");
elScript.setAttribute("src", sUrl);
elScript.setAttribute("id", sID);
document.getElementById("elHead").appendChild(elScript);


This does work on IE and FF, but on IE(8) the script is not available at once. It takes a while until it is registered (?). If I do an alert() after the include and then make use if the included methods, it works. So I would have to wait...but how? On FF(3) it is fine.

As workaround I tried

document.write('<script src="', sUrl, '" type="text/JavaScript" id="', sID, '"><\/script>');


for IE. This leads to very odd behavior and I also think it's "dirty".

Any ideas?

René

PeejAvery
June 10th, 2009, 12:51 PM
What odd behavior does your "workaround" produce? And why do you think that it is "dirty." I have used a similar method for years, and have seen many large corporations, such as Google and Yahoo do the same.

document.write('<scri' + 'pt type="text/javascript" src="' + jsFile + '"></scr' + 'ipt>');

Krumelur76
June 10th, 2009, 01:38 PM
Okay...if you say so.
What I do is:

<body onload="window.oMyObject = new MyObject()">
...here then the document.write() stuff happens...
<script language="Javascript">
window.oMyObject.DoIt();
</script>
</body>


In the last script block I get window.oMyObject is NULL on IE8. That's what I mean with "odd".

René

PeejAvery
June 10th, 2009, 01:56 PM
That makes sense to me since the page won't yet have fire the onload event. The onload event, since part of the body tag, fires after the body tag has been closed.