当我发布关于代码行为的答案时,我总是喜欢去两个地方:
- 规范
- 实现
规范:
DOM API明确指定脚本必须按顺序执行:
如果元素具有src属性,没有async属性,并且没有设置“force-async”标志,则该元素必须添加到与脚本元素的文档在准备脚本算法启动时相关联的尽快按顺序执行的脚本列表的末尾。
来自4.1 Scripting。请在使用defer
或async
属性之前检查此规则的例外列表。这在4.12.1.15中很好地规定了。
这是有道理的,想象一下:
var trololo = "Unicorn";
....
trololo = "unicorn";
var message = "Hello World";
alert(message);
通常最好使用模块加载器(它将延迟脚本插入和执行,并为您正确管理依赖项)。
目前,最好的方法是使用类似于Browserify或RequireJS的东西。在未来,我们将能够使用ECMAScript 6模块。
实现:
好吧,你提到了它,我无法抵挡。因此,如果我们检查Chromium blink源代码(在WebKit中仍然相似):
bool ScriptLoader::prepareScript(const TextPosition& scriptStartPosition,
LegacyTypeSupport supportLegacyTypes)
{
.....
} else if (client->hasSourceAttribute() && // has src attribute
!client->asyncAttributeValue() &&// and no `async` or `defer`
!m_forceAsync // and it was not otherwise forced
) { // - woah, this is just like the spec
m_willExecuteInOrder = true; // tell it to execute in order
contextDocument->scriptRunner()->queueScriptForExecution(this,
m_resource,
ScriptRunner::IN_ORDER_EXECUTION);
很好,我们可以从源代码中看到它们按照解析顺序添加 - 正如规范所述。
让我们看看
脚本运行器的操作:
void ScriptRunner::queueScriptForExecution(ScriptLoader* scriptLoader,
ResourcePtr<ScriptResource> resource,
ExecutionType executionType){
.....
// Adds it in the order of execution, as we can see, this just
// adds it to a queue
case IN_ORDER_EXECUTION:
m_scriptsToExecuteInOrder.append(PendingScript(element, resource.get()));
break;
}
使用定时器,它会在准备好的时候逐一触发它们(如果没有等待,则立即触发):
void ScriptRunner::timerFired(Timer<ScriptRunner>* timer)
{
...
scripts.swap(m_scriptsToExecuteSoon);
for (size_t i = 0; i < size; ++i) {
....
toScriptLoaderIfPossible(element.get())->execute(resource);
m_document->decrementLoadEventDelayCount();
}