Getting content of a script file using Javascript

If I understand you correctly, you don't want to use Ajax to load an html template text, but rather have it loaded with the rest of the page. If you control the server side, you can always include the template text in an invisible div tag that you then reference from Javascript:

<div id="template" style="display:none;">
...template text...
</div>
<script>
// pops up the template text.
alert(document.getElementById("template").innerHTML);
</script>

If you are just looking for to load the template so that you can have it cached, you can put the contents in a variable like this:

<script>
var template = "template text..";
</script>

or you can load it using ajax and store the template in a variable so it is accessible. It's pretty trivial in jquery:

var template;
$.get("template.html", function(data){
  template = data;
});

unless you load a script as literal text in the page, it does not exist as text. It is interpreted by the browser and melded into the runtime, with any other scripts.

If you want the source you have to fetch it again,if with Ajax get the responseText.

It will come from the browser cache, and doesn't have to be downloaded again.


I think what you want to do is to assign a variable inside template.js. Then you have the variable available for use wherever you want in jquery. Something like:

var tpl = "<div> ... </div>"

Wouldn't this be a simpler solution to your problem? We do this in Ext JS. I think this will work for you in jQuery.