开发者

If I run some code from linked javascript file does is execute before or after the dom?

Just wondering if I put code in a li开发者_开发知识库ked .js file is it the same as adding it in a

<script></script>

Tag.

And also is it like putting the script at the start or end of the document?


The only difference between using a script embedded in a document and using once srced from an external file is that one has to be loaded from an external source. A srced script at the start of a document is the same as any other script at the start, and one at the end is the same as any other at the end.

All scripts will block parsing of the HTML until the script has been loaded (from within the file or externally) and executed (although that execution might just be setting up event handlers to file later (e.g. onload).

(See, however, the defer attribute but note that browser support isn't universal)


Not the same when it comes to performance, since for external files, a browser needs to make an additional roundtrip to the server.

But when it comes to execution, a document.write() executes exactly after the script tag, regardless.

There is however, a defer parameter that lets you execute the JS at a later time.


Javascript code executes as it is encountered, unless explicitly specified otherwise. There is essentially no technical difference between on page Javascript and external sources.

Currently, if you do not employ some sort of asynchronous loading of JS assets, it is advisable to put them at the bottom of the file (unless of course you need the file in question as the page loads). As script files will essentially load 'back-to-back' and blocking any content that follows.

Most of the time JS is not required until the user begins interacting with the site. Placing JS files at the bottom also enables progressive rendering.

I think Steve Sauders summed it up best:

  • Deliver HTML

  • Defer JS

  • Avoid DOM

  • Decorate Later


It executes before DOM (yes, it blocks parsing unless loaded and executed) unless there is defer attribute, which standard method to tell UA what there is no document.write in the external file. Execution (with probable markup writing to the document stream) takes place immediately after any given <script> was encountered by parser.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜