vdh_ant
vdh_ant

Reputation: 13146

Getting content of a script file using Javascript

I have the following script element in my web page:

<script src="default.js" type="text/javascript"></script>

Using JavaScript, I want to be able to retrieve the content of the script file. I know I could use an ajax request to get the data but then I am getting something from the server that I already have locally.

So what I would prefer to do is retrieve the content from the DOM (if that's possible) or something that has the same result.

Cheers Anthony

UPDATE

I was trying to simplify the question, maybe a bad a idea, I thought this way would cause less questions.

The real situation I have is as follows, I actually have

<script type="text/html" class="jq-ItemTemplate_Approval">
   ...
   html template that is going to be consumed by jQuery and jTemplate
   ...
</script>

Now this works fine but it means each time the page loads I have to send down the template as part of the HTML of the main page. So my plan was to do the following:

<script src="template.html" type="text/html"></script>

This would mean that the browser would cache the content of template.html and I would not have to send it down each time. But to do this I need to be able to get the content from the file.

Also in this case, as far as I know, requesting the content via ajax isn't going to help all that much because it has to go back to the server to get the content anyway.

Upvotes: 13

Views: 20153

Answers (8)

The way that most JavaScript import files work is they include a script, that immediately calls a function with a parameter of certain text, or of another function. To better illustrate, say you have your main index.html file, set it up like this:

<html>
<head>
</head>
<body>
<script>
let modules = {};
function started(moduleName, srcTxt) {
    modules[moduleName] = (srcTxt) //or something similar
}
</script>

<!--now you can include other script tags, and any script tags that will be included, their source can be gotten (if set up right, see later)-->

<script src="someOtherFile.js"></script>
</body>
</html>

now make that other file, someOtherFile.js, and right away when its loaded, simply call that "started" function which should already be declared in the scope, and when thats done, then whatever text is passed, from the file, is stored in the main index.html file. You can even stringify an entire function and put it in, for example:

started("superModule", (function() {
    /*
    <?myCustomTemplateLanguage
    <div>
    {something}Entire Javascript / html template file goes here!!{/something}
    </div>
    ?>
    */
}).toString());

now you can access the inner content of the function, and get all the text in between the comments, or better yet, then do other parsing etc, or make some other kind of parsing identifiers at the beginning and end of the comments, as shown above, and get all text in between those

Upvotes: 0

oLinkWebDevelopment
oLinkWebDevelopment

Reputation: 1961

Using an iFrame & HTML5 Local Storage

Save the templates for rendering later...

not stoked about the iFrame, but it seems to be working pretty good (haven't ran performance tests yet)


Put the iFrame on the page you want the template on (index.html)

<html>
  <head>
    <iframe src="mustache.Users.html" onload="this.remove();" class="hidden" id="users_template"></iframe>
  </head>
</html>
  • Make sure the src attribute is set
  • hide the element until you can get rid of it after it loads

Put this body wrapper around your template (mustache.Users.html)

(don't worry it won't show up in the template)

<body onload="localStorage.setItem('users_template',this.document.body.innerHTML);"> 
  <ul class="list-group" id="users" >
    {{#users}}<li>{{name}}</li>{{/users}}
  </ul>
</body>
  • replace 'users_template' with whatever name for your variable
  • the 'onload' attribute saves the template into localStorage during load

Now You can access your templates from anywhere

localStorage.getItem('users_template')  

OR

window.localStorage.getItem('users_template')

check out this image to see it in Chrome

Upvotes: 1

Gareth Heyes
Gareth Heyes

Reputation:

You could get the attribute of the src of the script and then use XHR to get the contents of the JS file. It's a much cleaner way of doing it IMO. e.g.:-

if(window.XMLHttpRequest) {
                var xhr = new XMLHttpRequest();         
                xhr.onreadystatechange = function() {
                    if(xhr.status == 200 && xhr.readyState == 4) {
                        var sourceCode = xhr.responseText;
                                            alert('The source code is:-\n'+sourceCode);
                    }
                }
                xhr.open("GET",document.getElementById('scriptID').src,true);
                xhr.send(null);
            }

Upvotes: 2

Michael Siebert
Michael Siebert

Reputation: 2378

Why not use Ajax (well Ajah because its html :-))?

when the server is set up correctly and no no-cache or past expires headers are sent, the browser will cache it.

Upvotes: 0

Ryan Oberoi
Ryan Oberoi

Reputation: 14485

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.

Upvotes: 2

Helgi
Helgi

Reputation: 1577

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;
});

Upvotes: 5

kennebec
kennebec

Reputation: 104760

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.

Upvotes: 4

ICodeForCoffee
ICodeForCoffee

Reputation: 3226

What is in the JavaScript file? If it's actual code, you can run functions and reference variables in there just like you had cut and paste them into the webpage. You'll want to put the include line above any script blocks that reference it.

Is this what your looking to accomplish?

Upvotes: 0

Related Questions