Having Script within a Script Src tag? [removed] (

2020-07-13 10:38发布

Why does this not work?

<script type="text/javascript" src="//cdn.com/assets/js/jquery.js">
alert("Hello World!");
</script>

But this does?

<script type="text/javascript" src="//cdn.com/assets/js/jquery.js"></script>
<script type="text/javascript">
alert("Hello World!");
</script>

This is general across many HTML tags that pull from source. Micro optimization is important in my situation and I am also curious.

3条回答
冷血范
2楼-- · 2020-07-13 11:07

from http://javascript.crockford.com/script.html:

"If the src attribute is not present, then the content text between the <script> and the </script> is compiled and executed."

As there is a src attribute, the content is not executed

查看更多
够拽才男人
3楼-- · 2020-07-13 11:08

From w3.org (emphasis mine):

If the src has a URI value, user agents must ignore the element's contents and retrieve the script via the URI.

查看更多
该账号已被封号
4楼-- · 2020-07-13 11:11

In the first example you define the src which makes it IGNORE the contents of the <script></script>

In the 2nd example you have 2 separate <script></script> tags, the 2nd of which is housing your code to execute.

查看更多
登录 后发表回答