Why inline JavaScript is bad?
Asked Answered
R

9

28

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.

Redound answered 25/9, 2013 at 10:41 Comment(5)
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 JSSennar
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?Orlop
@RoryPicko92 a major advantage of all JS codes in one file is that it will be cached, and not needed to load through browsing.Redound
On top of that: Please check the recent attempt to establish "Content Security Policy" in browsers ... which will make external JS mandatoryOrlop
See also this excellent discussion: programmers.stackexchange.com/questions/86589/…Culp
U
44

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.

Unsightly answered 25/9, 2013 at 10:50 Comment(6)
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.Sixtieth
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.Verde
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.Aruwimi
Why can’t it cache the entire document including inline resources? Are you talking about caching for reusing?Juggins
Does it mean that if I put all js code into a function and into a separate file and just call this function inline than only that function name will be cached and it's ok independently of the function size? Or it is bad if the function definition is huge?Mook
Aren't HTML pages cached? If so, then I don't see why inline Javascript wouldn't also be cached.Yodle
C
20
  • 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.

Chime answered 25/9, 2013 at 10:51 Comment(1)
You can embed JS in your build process the same way you combine multiple JS files into one for deploymentBusyness
S
8

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.

Stab answered 25/9, 2013 at 10:45 Comment(0)
M
4

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.

Melanism answered 25/9, 2013 at 10:51 Comment(1)
getElementsByClassName is a lazy enumeration... (or "live" as they call it) it's not any work to just call it.Birthplace
Q
4

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

Quirt answered 11/6, 2020 at 9:32 Comment(0)
U
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

Underwent answered 25/9, 2013 at 10:52 Comment(0)
L
1

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.

Leiva answered 18/11, 2015 at 17:17 Comment(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 maintainabilityFermata
B
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.

Bentham answered 26/5, 2020 at 5:35 Comment(2)
What do you mean by "sense"? Can you put some explanation to your answer such that others can learn from it?Fermata
@NicoHaase probably, not worth the effort. loading a very small script from external file is not going to make any difference performance wise.Sibell
L
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.

Landloper answered 25/9, 2013 at 19:31 Comment(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.Melanism
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.Melanism
If we have required big js calculation with ajax then we have required otherwise we can add small functionality of js on page ofcourse.Landloper

© 2022 - 2024 — McMap. All rights reserved.