最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - <script defer> not working as expected - Stack Overflow

programmeradmin0浏览0评论

I am trying to defer my script execution because it is not important that it executes before the page is rendered. However, it is not working as I understand it.

According to this article (and others like it), if I use defer then the execution order is preserved. However, when using highlight.js I am seeing a different behaviour. My script files look like so:-

<script defer type="text/javascript" src="//cdnjs.cloudflare/ajax/libs/highlight.js/8.7/highlight.min.js"></script>
<script defer type="text/javascript">hljs.initHighlightingOnLoad();</script>

Now as I understand it they should execute in order which is unlike the behaviour of async. However, I get the following error in Chrome (version 44.0.2403.157).

If I remove the defer attributes it works as expected. What am I not understanding correctly?

I am trying to defer my script execution because it is not important that it executes before the page is rendered. However, it is not working as I understand it.

According to this article (and others like it), if I use defer then the execution order is preserved. However, when using highlight.js I am seeing a different behaviour. My script files look like so:-

<script defer type="text/javascript" src="//cdnjs.cloudflare./ajax/libs/highlight.js/8.7/highlight.min.js"></script>
<script defer type="text/javascript">hljs.initHighlightingOnLoad();</script>

Now as I understand it they should execute in order which is unlike the behaviour of async. However, I get the following error in Chrome (version 44.0.2403.157).

If I remove the defer attributes it works as expected. What am I not understanding correctly?

Share Improve this question edited Feb 8, 2017 at 15:05 CommunityBot 11 silver badge asked Aug 26, 2015 at 11:38 baynezybaynezy 7,07612 gold badges55 silver badges81 bronze badges 1
  • 1 wouldnt this only work if hljs.initHighlightingOnLoad() was also in an external file (and the loading of that file was "defer'd")? – atmd Commented Aug 26, 2015 at 11:43
Add a ment  | 

1 Answer 1

Reset to default 6

The defer attribute has been browser specific http://caniuse./#feat=script-defer (thanks to atmd)

The defer and async attributes must not be specified if the src attribute is not present.

Check your second case.

发布评论

评论列表(0)

  1. 暂无评论