Why inline JavaScript is bad?

前端 未结 9 817
梦谈多话
梦谈多话 2020-11-29 08:13

It is always recommended to avoid inline Javascript codes by putting all codes in a JS file, which is included in all pages. I wonder, if this does not cause pe

相关标签:
9条回答
  • 2020-11-29 09:09

    You should read about unobtrusive javascript, http://en.wikipedia.org/wiki/Unobtrusive_JavaScript.

    There are other solutions for not loading all the javascript files in your assets directory for each webpage, one called requirejs that should check out, http://requirejs.org/ .

    Moreover as a general rule of thumb you should not be adding all your event listeners when page loads, what about dom objects that don't exist? It will throw up javascript errors and will break your code more than usual.

    0 讨论(0)
  • 2020-11-29 09:12

    IMO it depends on the page. Sometimes for a specific page and script is small, it does not make sense to put in an external file.

    0 讨论(0)
  • 2020-11-29 09:13

    According to Addy Osmani's "The cost of JavaScript" presentation at #PerfMatters Conference 2019 one of the recommendation was to Avoid large inline scripts.

    Avoid large inline scripts (as they’re still parsed and compiled on the main thread). A good rule of thumb is: if the script is over 1 kB, avoid inlining it (also because 1 kB is when code caching kicks in for external scripts).

    So if you inline script is less then 1 KB - it's fine, otherwise - avoid it.

    Here is the source: The cost of JavaScript in 2019

    0 讨论(0)
提交回复
热议问题