编辑:抱歉,我应该更清楚。我的网页需要符合 XHTML。
我使用托管博客平台,我无法在上面托管 JavaScript 文件。我们通常像这样在网页上引用 JavaScript 文件:
<script type='text/javascript' src='http://example.com/js/mycode.js'></script>
问题是,我可以直接引用网页中的代码,而不是文件吗?如果是这样,我该怎么做?
只需将 JavaScript 代码粘贴到文件中
<script>
标记之间?<script type='text/javascript'> PASTE THE CODE FROM THE JS FILE HERE </script>
或者像这样?
<script type='text/javascript'> //<![CDATA[ PASTE THE CODE FROM THE JS FILE HERE //]]> </script>
以上两种方法哪个是正确的?如果没有,是否有更好的方法?
此外,是否可以像这样在脚本标记内引用文本 (.txt) 文件?
<script type='text/javascript' src='http://example.com/js/mycode.txt'></script>
或者我这样做会不会有什么问题?
寻找知识渊博的答案。
最佳答案
Can I directly reference code in the web page, instead of the file?
是的,您可以将代码粘贴到 <script>
标记之间。 HTML 甚至允许裸脚本标记,因为浏览器会忽略 language
属性和 type
属性 can be omitted according to spec。
The type attribute gives the language of the script or format of the data. If the attribute is present, its value must be a valid MIME type. The charset parameter must not be specified. The default, which is used if the attribute is absent, is "text/javascript".
所以你可以这样:
<script>
//your code
</script>
此外,您还可以选择在外部托管您的脚本,而改用它
<script src="http://externalhost.com/yourscript.js"></script>
Also, can a text (.txt) file be referenced inside a script tag, like this?
据我所知,您可以将任何纯文本 作为您的来源,浏览器默认会将其读取为 JavaScript。偶 text from pastebin can act like a script.
关于javascript - 使用 JavaScript 代码而不是引用文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10748057/