Zach
Zach

Reputation: 19082

How can I read the contents of a linked script into a String?

I am able to select a linked script element. Is there a way to read the contents into a string?

I have jQuery available.

Upvotes: 0

Views: 80

Answers (5)

aziz punjani
aziz punjani

Reputation: 25776

It depends if the script is embedded or linked.

For embedded javascript you could do

var test = $('script').eq( index_here ).text(); 

For an external javascript file with a source attribute, you could perform an ajax request and get the contents.

Upvotes: 1

Krzysztof
Krzysztof

Reputation: 16140

You can do ajax request and pass script url (src attribute). Server will return js source. Example:

var script = $('selector');
var src = script.attr('src');

if (src.indexOf('://') == -1) {
    src = document.location.href.substr(0, document.location.href.lastIndexOf('/') + 1) + src;
}

$.get(src, {}, function(data){
    // do something
});

Upvotes: 3

John Hartsock
John Hartsock

Reputation: 86882

Never tried this before but if you get the script such as

$(scriptselector).text()

Edited.

Just tried it and it seems to work http://jsfiddle.net/UG3hB/

Edit #2:

As Intersteller_Coder pointed out this will not work with linked jsfiles. You can always request the js file via AJAX.

Upvotes: 1

Gabriel Gartz
Gabriel Gartz

Reputation: 2870

Yes, just get the innerText or innerHTML from the element reference.

Upvotes: 0

Royi Namir
Royi Namir

Reputation: 148524

$("<div/>").append($("#myAnchor")).text();

Upvotes: 0

Related Questions