简体   繁体   English

使用HTML5包含JavaScript的最小字符<script> tag

[英]Minimum characters to include JavaScript using HTML5 <script> tag

Now that the type attribute of the <script> tag can be omitted in HTML5, is this the fewest number of characters required to include external JavaScript on a page? 现在在HTML5中可以省略<script>标记的type属性,这是在页面上包含外部JavaScript所需的最少字符数吗?

<script src="URL"></script>

Can anyone optimise it any more than this - what about if a framework such as jQuery was already loaded, is there an even shorter way? 任何人都可以对此进行更多优化-如果已经加载了jQuery之类的框架,还有没有更短的方法呢?

If you don't care about the JavaScript being able to reach out and access page content, then 如果您不关心JavaScript是否能够访问并访问页面内容,那么

<img src="URL.svg">

where the URL points to an SVG image that uses SVG scripting would allow you to load a script and you could call functions defined in it by sending events to the SVG image to trigger event handlers. 如果URL指向使用SVG脚本的SVG图像,则将允许您加载脚本,并且可以通过将事件发送到SVG图像来触发事件处理程序来调用其中定义的函数。

You may be able to get around that restriction by using an SVG served from the same origin but I believe the security consequences of same-origin access for SVG are poorly understood so spec and browser writers are treading cautiously. 通过使用来自相同来源的SVG,您也许可以解决该限制,但是我认为对SVG的相同来源访问的安全后果了解得很少,因此,规范和浏览器作者都在谨慎从事。

You could omit the quotes for the attribute : 您可以省略属性的引号

<script src=URL></script>

As well, with XHTML5 the following should work: 同样,使用XHTML5,以下功能也可以工作:

<script src="URL" />

Since you asked about jQuery, you can use $.getScript() : 由于您询问了jQuery,因此可以使用$.getScript()

$.getScript("f.js");

Of course this assumes your code has already been wrapped, or loaded in via in <script> tags. 当然,这假定您的代码已经被包装或通过<script>标记加载。 To be honest, there really isn't much benefit in trying to shave off a few more bytes in this area. 老实说,在该区域中尝试删除更多字节确实没有太大好处。 It's not like referencing scripts requires a great deal of verbosity anyway. 无论如何,引用脚本并不需要大量的冗长。

Keep your code readable, and don't deviate too far from standards and accepted conventions. 保持代码可读性,并且不要偏离标准和公认的惯例。

[from my comments] [根据我的评论]

Supposing you already handled script aggregation using for example the excellent Google Closure Compiler and you don't want to use the heavy js loading libraries, a simple optimization is this : 假设您已经使用出色的Google Closure Compiler处理了脚本聚合,并且您不想使用繁重的js加载库,那么一个简单的优化就是这样:

<script src=a></script>

(no quote, no ".js", yes that's silly) (没有引号,没有“ .js”,是的,这很愚蠢)

Of course, you can also remove spaces and CR before and after this part. 当然,您也可以在此部分前后删除空格和CR。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM