Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read content of external script tag with jquery

A common pattern for loading backbone templates is something like:

<script type='text/template' id='foo'>
    my template
</script>

----
var whatever = $('#foo').html();

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

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

But the html() of foo is now empty.

I watched the browser pull the template file down, but I am not sure if it is in the page dom or not. Is there a simple way to reference the content of the script in javascript, or did the browser simply ignore it and throw out the result?

like image 844
captncraig Avatar asked Mar 15 '12 17:03

captncraig


2 Answers

I think to actually execute externally loaded script you have to do an eval() of the contents. You're not adding it to the DOM really since it's script, you're adding it to the JS runtime. There might be other ways of doing it but eval() is generally considered a security hole since malicious code could be evaluated.

What I tend to do is generate template sections on the server so I know all my JS is there when the DOM is ready.

like image 150
FlavorScape Avatar answered Nov 12 '22 16:11

FlavorScape


If the point is execute an action just after the script has been loaded you can put a onload attribute on the script tag. If you want to download the content in runtime, then you could use the async download strategy (like Gats pointed).

It´s important keep in mind some important points when using templates for jquery templates in external files, there is an interesting article about jquery templates with external files, you must check it.

like image 31
Adilson de Almeida Jr Avatar answered Nov 12 '22 16:11

Adilson de Almeida Jr