IlanKogan
IlanKogan

Reputation: 137

jquery ajax removes line break on GET

I need to dynamically load a JavaScript file from a remote URL but I must make some changes to the received script before I'm appending it to the header.

The problem is: I'm getting the content of the JS file without the line breaks, so if there are some comments inside - all the script stops to work..

The code I used is:

        $.ajax({
            url: filename,
            type: "GET",
            success: function (res) {
                var ver = $(res.responseText);
                var jsContent = $(ver).text();

                jsContent = jsContent.replace('..', '...');

                var oScript = document.createElement("script");
                oScript.language = "javascript";
                oScript.type = "text/javascript";
                oScript.defer = true;
                oScript.text = jsContent;
                document.getElementsByTagName("head")[0].appendChild(oScript);
            }
        });

Any ideas?

Upvotes: 2

Views: 794

Answers (1)

Patrick Evans
Patrick Evans

Reputation: 42736

if you are just trying to dynamically load a js file, then you need to set the datatype to "script" or use the .getScript functions

    $.ajax({
        url: filename,
        type: "GET",
        dataType:"script",
        success: function (res) {

        }
    });

or

    $.getScript(url);

http://api.jquery.com/jQuery.getScript/

Upvotes: 5

Related Questions