user656925
user656925

Reputation:

Pulling already loaded JS into a local variable

The source of linked to .js is not available via the DOM currently.

var b = document.createElement("script");
b.type= "text/javascript";
b.src = "foo/source/ArcJ.js"  // dynamically load .js file

Can I just do

var c = b.src // probably not

I think this would just give me the path...I want the source...i.e. all the code in a string.

Is there a way to do this with out using ajax? Shouldn't this be a simple DOM Pull...

document.getElementById(b.id).source_code

?

Upvotes: 0

Views: 160

Answers (2)

Shanimal
Shanimal

Reputation: 11718

.src is the url, so you just load the url from that using an ajax request...

$.get($("script[src*=jquery]").attr("src"),function(data){
    console.log(data)
})

Upvotes: 2

Alexandre Khoury
Alexandre Khoury

Reputation: 4022

Took from How do I get source code from a webpage? (written by me)

There is three way in javascript :

Firstly, by XMLHttpRequest : http://jsfiddle.net/635YY/1/

var url="../635YY",xmlhttp;//Remember, same domain
if("XMLHttpRequest" in window)xmlhttp=new XMLHttpRequest();
if("ActiveXObject" in window)xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
xmlhttp.open('GET',url,true);
xmlhttp.onreadystatechange=function()
{
    if(xmlhttp.readyState==4)alert(xmlhttp.responseText);
};
xmlhttp.send(null);

Secondly, by iFrames : http://jsfiddle.net/XYjuX/1/

var url="../XYjuX";//Remember, same domain
var iframe=document.createElement("iframe");
iframe.onload=function()
{
    alert(iframe.contentWindow.document.body.innerHTML);
}
iframe.src=url;
iframe.style.display="none";
document.body.appendChild(iframe);

Thirdly, by jQuery : http://jsfiddle.net/edggD/2/

$.get('../edggD',function(data)//Remember, same domain
{
    alert(data);
});

Upvotes: 0

Related Questions