You want to dynamicly load js files, but what's the best solution between an XMLHttpRequest + eval (the answer) and DSL solution ?
This is the first solution : DSL.
the dslTST.txt is a hudge js file : it's mootools core duplicatide many times (2.377 mo)
At the end of the file, we have the instruction : chrono.stop(0); which will stop the chrono.
chrono.start(0);
var DSLScript = document.createElement("script");
DSLScript.src = "dslTEST.txt";
DSLScript.type = "text/javascript";
document.body.appendChild(DSLScript);
The first solution only timed during the evalution of the script by the browser.
At the top of the file, I add the instruction : chrono.start(0); which will start the chrono.
var DSLScript = document.createElement("script");
DSLScript.src = "dslTEST.txt";
DSLScript.type = "text/javascript";
document.body.appendChild(DSLScript);
The second solution :
chrono.start(1) ;
var myRequest = new Request({
method: 'get',
url: 'dslTEST.txt',
onSuccess: function (responseText, responseXML) {
eval (responseText) ;
chrono.finish(1);
}
});
myRequest.send();
The second solution timed during the eval() function :
var myRequest = new Request({
method: 'get',
url: 'dslTEST.txt',
onSuccess: function (responseText, responseXML) {
chrono.start(1) ;
eval (responseText) ;
chrono.finish(1);
}
});
myRequest.send();
The speed results are quite suprising (in ms) :

So what's the conclusion ?
DSL seems to be faster for big files. (I have run the same tests with "small" files (e.g. 1x mootools core), and there is no real difference.)
Comparison DSL with XMLHttpRequest()
This method of loading Javascript code or data by dynamically creating new <script> tags in the header does have some advantages over XMLHttpRequest() calls:
- Seems really faster for big files.
- Can request a file from anywhere on the net, not just the server your page was loaded from (whithout cross-domain problems, but it can be fixed using other solution than XMLHttpRequest.
- Works in IE even when ActiveX is turned off (though not when Javascript is turned off).
- Works with a few older browsers that don't support XMLHttpRequest, like Opera 7 (though not Macintosh versions of IE).
There are also some modest disadvantages, including:
- Returned data has to be formatted as Javascript code. XMLHttpRequest() can be used to fetch data in any format, XML, JSON, plain text, or whatever.
- Can only do GET requests, not POST requests.
- Whether the request is synchronous or asynchronous is pot luck, depending on the browser. With XMLHttpRequest() you can control this.
- When fetching JSON data from an untrusted source, there is no possiblity of checking the data before feeding it to the Javascript parser. With XMLHttpRequest() you can parse the data with something like json2.js instead of eval() for secure parsing.
Conclusion inspired by this post.