Why inline JavaScript is bad?

前端 未结 9 885
梦谈多话
梦谈多话 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 08:59

    It's possible that running unnecessary JavaScript on a page will cause that page to be slow to load. It depends on the JavaScript being run.

    You could test your example code by timing it, and seeing how long it takes for JavaScript to run getElementsByClassName repeatedly.

    (I'd bet it doesn't take very long at all, even if you've got 26 functions looking for elements with different class names, but with performance, always measure first.)

    If execution time is a problem, you could write your JavaScript so that it's mostly in one file, but expose functions that you run from inline JavaScript on the pages it's required on, instead of running it via onload events in your JavaScript file.

    It's worth remembering everything that has to happen when a page is loaded though:

    1. The browser fetches the page from its cache, or sends an HTTP request to see if the page has changed since it was cached, and/or sends an HTTP request for the page itself.
    2. The browser parses and renders the page, pausing to fetch and run any external JavaScript, and fetching stylesheets and images concurrently with parsing and rendering.
    3. The browser runs any JavaScript set to run on document ready.
    4. The browser runs any JavaScript set to run on page load.

    Although you certainly can write JavaScript that runs slowly, it's likely that it's better overall to have your JavaScript in an external file, and therefore in the user's browser's cache, rather than having it increasing page size by being inline. Network, in general, tends to be much slower than JavaScript parsing/execution.

    But, and I'm saying this again because it's the most important point, this will all be different depending on your code. If you want to keep your performance good, your first and last act must be to measure it.

提交回复
热议问题