此外,何时加载代码,设置.src
属性或附加元素。举例说明:
var test = document.createElement('script');
test.src = 'some_path';
// is code loaded here?
document.head.appendChild(test);
// or here?
...
// or is it an asynch operation?
答案 0 :(得分:4)
在动态创建脚本元素时,在将元素插入文档之前,不会加载或执行源文件。加载脚本异步。这意味着您的代码执行以下操作:
编辑:感谢您指出设置 async 属性对脚本的加载行为没有任何影响。我从来没有真正使用它,并认为它会工作,但它显然没有。我删除了声称会这样做的部分。 I made an example to show this
答案 1 :(得分:1)
Javascript从上到下运行,除非它是一个函数,对服务器的异步调用,或者在等待某个事件的闭包中(即:window.load()
)
您的代码如下:
var test = document.createElement('script');
//declare variable test to create script element
test.src = 'some_path';
//define element with src attribute 'some_path'
document.head.appendChild(test);
//place script element in head block
虽然我建议在服务器端创建动态脚本块,以避免由于异常和高负载/超时可能性引起的复杂情况。
您可以在Firebug和Chrome Dev工具中插入断点,以逐步完成脚本并查看正在发生的事情。更多信息:https://developers.google.com/chrome-developer-tools/docs/javascript-debugging