动态加载脚本
通过向DOM中动态添加script元素加载指定脚本
let script = document.createElement(‘script‘);
script.src = ‘example.js‘;
script.async = false;//这种方式创建的<script>默认添加了async属性,因有的浏览器不支持async属性,将其改为同步
document.head.appendChild(script);
以这种方式获取资源对浏览器预加载器不可见,影响其在资源获取队列中的优先级,可能影响性能,要想让预加载器知道这些动态请求的文件,可在文档头部显式声明:
<link rel="preload" href="example.js"></link>
xhtml中的变化
xhtml是将html作为xml的应用重新包装的结果
xhtml中使用javascript必须指定type=text/javascript
xhtml比html中代码规则更严格,在html中解析<script>元素会应用特殊规则,xhtml中则没有这些规则,如以下代码:
在html中:
<script type="text/javascript">
function compare(a, b){
if(a < b){
console.log("a less than b");
}else if(a > b){
console.log("a greater than b");
}else{
console.log("a equal to b");
}
</script>
xhtml中:
<script type="text/javascript">
function compare(a, b){
if(a < b){
console.log("a less than b");
}else if(a > b){
console.log("a greater than b");
}else{
console.log("a equal to b");
}
</script>
或
<script type="text/javascript">
//<![CDATA[ //支持在不支持xhtml的浏览器中优雅降级
function compare(a, b){
if(a < b){
console.log("a less than b");
}else if(a > b){
console.log("a greater than b");
}else{
console.log("a equal to b");
}
//]]>
</script>
注:xhtml模式会在页面的MIME类型被指定为"application/xhtml+xml"时触发。但并不是所有浏览器都支持以这种方式送达xhtml
废弃的语法
type属性使用一个MIME类型字符串来标识<script>内容,但MIME类型并没有标准化。某个无效或无法识别的MIME类型也可能导致浏览器跳过相关代码。因此除非使用xhtml或<script>标签要求或包含非javascript代码,最佳做法是不指定type属性
<script>标志着与传统html解析不同的流程,应用特殊的解析规则。以如下方式在不支持javascript的浏览器中保持兼容:
<script><!--
function sayHi(){
console.log("Hi");
}
//--></script>
但在xhtml模式下,会导致脚本被忽略
原文:https://www.cnblogs.com/songqt/p/14142408.html