且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

HTML标签如何在脚本标签内工作?

更新时间:2023-12-05 21:49:28

You can put anything that you want in a <script> tag. If you specify a content type other than Javascript (or another scripting language that the browser understands), it will not be interpreted by the browser, and you can just access it as plain text. Since the contents of <script> tags are treated as CDATA, the contents are not parsed and you can store unquoted XML or HTML in the contents (as long as you don't ever put a </script> tag in the contents, since that will close your element).

This is used, for example, in SVG Web, a polyfill that allows you to use inline SVG in HTML and have that converted to native SVG in browsers that support it, or Flash in browsers that don't. It allows embedding of SVG in browsers that don't support it natively by wrapping it in a <script> tag, so the browser doesn't try and fail to parse it as HTML.

In the case of SO carreers, it looks like they storing templates for use with Backbone.js and Underscore.js in <script> tags, since that's a convenient place to stick templates in HTML. Here's a snippet of their code where they grab the template and provide it to the Underscore template engine:

    TopAnswerView = Backbone.View.extend({
        template: _.template($("#topanswer").html()),
        events: {
            "click .add-answer": "addAnswerToCV"
        },