Reading the contents of an external script tag using jquery

A common template for loading basic templates is:

<script type='text/template' id='foo'> my template </script> ---- var whatever = $('#foo').html(); 

I would like to include the script in an external file as follows:

 <script type='text/template' id='foo' src='myTemplate.tpl'></script> 

But html() of foo now empty.

I watched the browser pull out the template file, but I'm not sure if it is on the dom page or not. Is there an easy way to reference the contents of a script in javascript or is the browser just ignoring it and throwing the result?

+7
source share
2 answers

I think that in order to actually execute the script loaded from outside, you need to do an eval () of the content. You do not add it to the DOM, since it is a script, you add it to the JS runtime. There may be other ways to do this, but eval () is usually considered a security hole, as malicious code can be evaluated.

What I usually do is generate sections of templates on the server, so I know that all my JS exist when the DOM is ready.

+2
source

If the dot starts immediately after loading the script, you can put the onload attribute in the script tag. If you want to download content at run time, you can use the async download strategy (e.g. Gats point).

It is important to remember some important points when using templates for jquery templates in external files, there is an interesting article about jquery templates with external files, you should check it out.

+1
source

All Articles