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?


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.


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.

链接地址: http://www.djcxy.com/p/10550.html

上一篇: JQueryUI对话框TinyMCE问题

下一篇: 用jQuery阅读外部脚本标签的内容