Running JavaScript downloaded with XMLHttpRequest Running JavaScript downloaded with XMLHttpRequest ajax ajax

Running JavaScript downloaded with XMLHttpRequest


I believe the recommended solution is something like this:

function include(scriptUrl){    var xmlhttp = new XMLHttpRequest();    xmlhttp.open("GET", scriptUrl);    xmlhttp.onreadystatechange = function()    {        if ((xmlhttp.status == 200) && (xmlhttp.readyState == 4))        {            eval(xmlhttp.responseText);        }    };    xmlhttp.send();}

Or something like it.

However, be wary of this approach. It's vulnerable to cross-site scripting, which can open you (and your users) up to all sorts of nastiness. You'll want to take suitable precautions.


Recently I found the answer (It works in Chrome, in another browsers it was not tested).

You can create dataURL string and put it into src attribute of script element.

var xhr = XMLHttpRequest(),    doc = document;xhr.open('GET', pathToJSFile, true);xhr.onload = function () {    var script = doc.createElement('script'),        base64 = 'data:application/javascript;base64,';    try {        base64 += btoa(data.responseText);    } catch (e) {        // script file may contain characters that not included in Latin1        var symbols = data.responseText.split('');        for (var i = 0, l = symbols.length; i < l; i++) {            var symbol = symbols[i];            // here we are trying to find these symbols in catch branch            try {                btoa(symbol);            } catch (e) {                var code = symbol.charCodeAt(0).toString(16);                while (code.length < 4) {                    code = '0' + code;                }                // replace original symbol to unicode character                symbols[i] = '\\u' + code;            }        }        // create new base64 string from string with replaced characters        base64 += btoa(symbols.join(''));    } finally {        script.src = base64;        // run script        doc.body.appendChild(script);    }};xhr.send();

You can subscribe to xhr.onprogress to show progress bar.

Update. You can download your script file as blob, and then create blob-url.

var xhr = XMLHttpRequest(),    doc = document;xhr.responseType = 'blob';xhr.open('GET', pathToJSFile, true);xhr.onload = function () {    var script = doc.createElement('script'),        src = URL.createObjectURL(xhr.response);    script.src = src;    doc.body.appendChild(script);};xhr.send();


You can run script downloaded in form of a string using

eval()

However I would recommend you to add new

<script src='..'></script>

to your document and have a callback which will be called when it will be downloaded. There are many utils and jquery plug-ins for that.