27

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 performance problem in heavy pages.

For example, imagine that we have tens of functions like this

function function1(element){
var el=document.getElementsByClassName(element);
var size=el.length;
if(size==0) return;
for(i=0;i<size;i++){
// the process
}
}

on every page, we need to run the functions to know if there are corresponding elements in the HTML or not.

window.onload = function(){
function1('a');
....
function26('z');
};

but if keeping all functions in an external JS file, and calling functions through inline JavaScript, we can call only the functions, which are required in the present page:

<script type="text/javascript">
window.onload = function(){
function6('f');
};
</script>

Doesn't it beneficial from performance point of view to call functions via inline Javascript (which is of course not best practice) to avoid call of lots of functions, which are not needed in a page?

Of course, this is not limited to functions only, as we have lots of addEventListeners for the entire website, which are fired on each and every page, where they are not needed.

5
  • 3
    You could have multiple external JS files with all your funcationality and then specific files for each page. which would hold what would normally be inline JS
    – rorypicko
    Sep 25, 2013 at 10:45
  • Noone ever said that each and every function of your whole site needs to be in one Javascript file ... why should there be any difference in the amount of code in your external JS file compared to your "inline" Javascript?
    – devnull69
    Sep 25, 2013 at 10:48
  • @RoryPicko92 a major advantage of all JS codes in one file is that it will be cached, and not needed to load through browsing.
    – Googlebot
    Sep 25, 2013 at 10:48
  • 1
    On top of that: Please check the recent attempt to establish "Content Security Policy" in browsers ... which will make external JS mandatory
    – devnull69
    Sep 25, 2013 at 10:50
  • 1
    See also this excellent discussion: programmers.stackexchange.com/questions/86589/…
    – cssyphus
    Mar 19, 2015 at 11:00

9 Answers 9

43

It's not recommended to inline static resources (in your case, the inline javascript) since you can't cache them.

Caching a static resource reduces the size of page loads – thus increasing the page load speed – for returning visitors. However it comes at the cost of an additional HTTP request which should be avoided.

Whenever the static resource is so small that the additional size is negligible in comparison to a HTTP request, then it's actually recommended to keep that resource inline.

It's usually a good idea to keep javascript libraries in external (cacheable) documents, while keeping small amounts of scripts inline.

So, in response to your headline – inline javascript isn't bad per-se. It's a balance whether or not it's worth a HTTP request to cache the resource.

6
  • 2
    Whilst there are many other valid concerns, this is the correct answer to the question, and by far the most impacting concern when choosing inline vs external.
    – Billy Moon
    Sep 25, 2013 at 19:36
  • This is a really good answer. I had just a discussion with someone about this, and I reasoned about that it was about balance. There is a lot of blogs out there that says inline is bad, but I couldn't agree with their reasoning. I use a lot of inline snippets that will only run on one single page. More generic snippets that is more reusable is put into a single js file that is included for every page. Jan 30, 2016 at 11:30
  • In this case of an external file it can be downloaded in paralell and served via an edge cache like cloudfront. So the performance impact of not inlining in negible enough to say that its rarely a good idea since its messy.
    – max
    Nov 22, 2017 at 18:15
  • 1
    Why can’t it cache the entire document including inline resources? Are you talking about caching for reusing? Aug 17, 2019 at 18:29
  • 1
    Aren't HTML pages cached? If so, then I don't see why inline Javascript wouldn't also be cached.
    – Asker
    Jun 24, 2023 at 11:32
19
  • Avoiding inline js is not performance based...but its more about maintainability and separating the presentation layer(html) from the controller layer(js).

  • Having inline js on different pages will make it difficult to maintain for you and others as the project scale increases.

  • Moreover using separate js files you can encourage reusability and modular code design.

  • keeps your html clean and you know where to look when any js error occurs instead of multiple templates.

1
  • You can embed JS in your build process the same way you combine multiple JS files into one for deployment
    – user317033
    Jun 7, 2017 at 4:03
7

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.

3

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.

1
  • getElementsByClassName is a lazy enumeration... (or "live" as they call it) it's not any work to just call it.
    – Esailija
    Sep 25, 2013 at 18:05
3

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

1

there are variuos case that needs to be keep in mind while placing js code.

For inline :

  1. there is no need to navigate to an external file if you need to change something quickly, so its better in locality

  2. if you are using AJAX in some elements of your page you may loose all the dom element onclick etc for that section, that obviously depends on how you binded them. for ex you can use live or delegate in case your using jQuery to avoid above said problem... but i find that if js is small enough it is preferable to just put it inline.

Now there other theory for ex

Externalizing javascript is one of the yahoo performance rules:

http://developer.yahoo.com/performance/rules.html#external

1

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.

2
  • What do you mean by "sense"? Can you put some explanation to your answer such that others can learn from it?
    – Nico Haase
    Jun 11, 2020 at 9:37
  • @NicoHaase probably, not worth the effort. loading a very small script from external file is not going to make any difference performance wise. Sep 18, 2023 at 12:45
0

Making js inline to all pages make the application heavy so we should go with external js which includes to require pages that will help us to utilization of js code to each functionality.

3
  • Depends on the JavaScript though, doesn't it. For example, in a site I run, I use this script inline just after the body tag: <script>(function (body_el){body_el.className=body_el.className.replace('no-js','js');})(document.getElementsByTagName('body')[0]);</script>. It's 141 bytes, and that's before gzipping. Not particularly heavy, and I think it's the fastest way to change a class on the body, as there isn't any JavaScript event that fires after the body tag is rendered. Sep 26, 2013 at 9:41
  • Also: "which includes to require pages that will help us to utilization of js code to each functionality" - I don't know what that means. Sep 26, 2013 at 9:41
  • If we have required big js calculation with ajax then we have required otherwise we can add small functionality of js on page ofcourse. Oct 17, 2013 at 9:14
0

Inline styles/script gets muddled with html content and can get hard to differentiate. One of the the keys to having maintainable code in web development is writing code that is easily readable by someone who didn't write it. Mixing script tags into your html can make it very hard to find a function that is affecting the rest of you code. Putting Javascript in .js files and Styles in CSS files makes code cleaner more readable.

1
  • Using current JS techniques like concatenating all stuff into a large JS application file, it's not that easy to spot the problem either. And the main question was about performance, not about maintainability
    – Nico Haase
    Jun 11, 2020 at 9:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.