views:

17

answers:

2

Greetings,

my xul app needs to load scripts dynamically, for this I derived a function that works in regular html/js apps :

function loadScript(url)
{
  var e = document.createElement("script");
  e.src = url;
  e.type="text/javascript";
  document.getElementsByTagName("head")[0].appendChild(e); 
}

to something that ought work in XUL :

function loadScript( url)
{
    var e = document.createElement("script");
    //I can tell from statically loaded scripts that these 2 are set thru attributes
    e.setAttribute( 'type' , "application/javascript" );  //type is as per MDC docs
    e.setAttribute( 'src'  , url );
    //XUL apps attach scripts to the window I can tell from firebug, there is no head
    document.getElementsByTagName("window")[0].appendChild(e); 
}

The script tags get properly added, the attributes look fine,but it does not work at all, no code inside these loaded scripts is executed or even parsed.

Can any one give a hint as to what might be going on ?

T.

+1  A: 

I've tried this, and I think you're right - I can't seem to get XUL to run dynamically appended script tags - perhaps it's a bug.

I'm curious as to why you would want to though - I can't think of any situation where one would need to do this - perhaps whatever you're trying could be achieved another way. Why is it they need to be dynamically loaded?


Off-topic: on the changes you made to the script.

e.setAttribute('src',url); is valid in normal webpages as well, and is actually technically more "correct" than e.src=url; anyway (although longer and not well supported in old browsers).

Types application/javascript or application/ecmascript are supposed to work in normal webpages and are more "correct" than text/javascript, but IE doesn't support them so they're not normally used.

lucideer
Greetings, I am doing some pretty messed up stuff; I get badly formed javascript, load it dynamicall in XUL, have firefox tell me what is wrong on which line number, have my XUL script analyze the error, fix the badly formed javascript to make it a little better and keep loading/fixing until the javascript works.
tomdemuyt
+1  A: 

Okay,

as usual whenever I post on stack overflow, the answer will come pretty soon thru one last desperate Google search.

This works :

//Check this for how the url should look like :
//https://developer.mozilla.org/en/mozIJSSubScriptLoader
function loadScript( url)
{
  var loader = Components.classes["@mozilla.org/moz/jssubscript-loader;1"].getService(Components.interfaces.mozIJSSubScriptLoader); 
  //The magic happens here
  loader.loadSubScript( url ); 
}

This will only load local files, which is what I need for my app.

I am fairly disappointed by Mozilla, why not do this the same way like html, in a standard way ?

tomdemuyt
Where would the challenge be in that? ;)
lucideer