Return script content that has src attribute
i am having a bit of a problem here and i don't even know if it is possible at all, here's my dilema:
I have this script code:
<script id='script1' src='http://link.to.js'></script>
While using firebug, i can clearly see that the script has bee loaded between those tags, like this
<script id='script1' src='http://link.to.js'>
function something(){
alert('hi');}
</script>
What i want to do is, by means of another script, get the content between those tags, something like
var x = document.getElementById('script1').innerHtml;
document.getElementById('somedividhere').innerHtml = x;
That works perfectly WHEN the code is already part of the开发者_JAVA百科 html, not when its loaded from src.
I have been looking for this for hours and i have not found any hint, hope someone can help me on this.
I think Firebug only shows you that for convenience sake. If you want to get the code from the script, you'll have to use AJAX.
You could do something like this:
function ajaxFunction(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var scriptcontent = ajaxRequest.responseText;
//Do something with the content
}
}
ajaxRequest.open("GET", document.getElementById('script1').src, true);
ajaxRequest.send(null);
}
Just a few notes:
- This will only work for scripts located on your site due to the same origin policy.
- I took the ajax code from this site and modified it.
- This would be a lot easier with jQuery
精彩评论