Is there any good reason for javascript to be inline [duplicate]
Asked Answered
E

11

5

I've been building a site. At some stage I noticed that IE display was a little broken and Chrome had all but rendered nothing but the body tag (empty), and FF all looked good.

After throwing my keyboard around the room and bashing my head against my mouse, I discovered the problem. I had left (don't ask how or why, must have been some lightning speed cut and paste error) an HTML comment unclosed in an inline script block.

<script type="text/javascript">
        <!--
        ...
    </script>

I'm guessing (not tested) the problem would have either not come up, or manifested itself in a far more noticeable way if the script was external. So anyways, I got to thinking, is there ever a time when you have a really good reason to write inline script??

Entomologize answered 30/6, 2009 at 15:0 Comment(3)
There's no point in using HTML comments within script tags. They were needed back when Netscape Navigator 2 was new (around 1996) to prevent older browsers displaying the script as text. This hasn't been a problem for well over ten years now, so don't bother with them.Copro
yeah i know. It was a complete error. I don't use them in js, thats why i mentioned that it must have been a result of a cut-and-paste frenzy. :-( i.e DOH!Entomologize
Please consider new answers to your question. While Unobtrusive Javascript is certainly the aim of all programmers, it is not always possible - and I read your question as not "in a perfect world..." but rather "is there ever a situation"Prepense
H
9

No. Write Unobtrusive Javascript.

Hephzipah answered 30/6, 2009 at 15:2 Comment(9)
I'm a big fan of unobtrusive javascript as well.Asymptomatic
Some frameworks to help get you started are: jQuery, YUI, Prototype, MooTools, Dojo.Omaromara
It's not impossible to write unobtrusive javascript without a good framework like the ones you listed, but why would you want to? :)Hephzipah
sitepoint.com had another good article on that - can't find the link ATMStesha
I have long agreed with the unobtrusive as a whole, though still at times write some 'obtrusive' js. So I guess the reason inline js is still around then is 'because thats the way we've done it'. hmm, yeah, cr@p reasonEntomologize
What do the principles of unobtrusive javascript have to do with putting scripts inline? You can progressively enhance your pages using inline scripts or external scripts so I would put this comment into the "correct but irrelevant" category. I realize that the chapter you linked mentions using external scripts, but it also give no reasons whatsoever for doing so.Latialatices
No reasons whatsoever? What about "...you can apply one collection of functions to every page of the site, and if you need to change its functionality, you can do that in one document rather than going through each page."Hephzipah
@mgroves: You're right, my bad. However, there is still nothing about progressive enhancement and "unobtrusiveness" that is dependent on having external scripts. I will agree that it is the best practice (for caching benefits, code reuse, maintainability, etc.) but external scripts are not necessary for staying unobtrusive.Latialatices
A fair point, but I think that having a bunch of JS in the same file as the HTML is obtrusive to me as a developer, or even to a designer. I would say if it's just a couple lines of jQuery, it's fine, but in my experience that code rarely stays a couple lines.Hephzipah
A
4

If you want your Javascript to run as early as possible, it might make sense to include inline Javascript, since it will run before any other HTTP requests have necessarily completed.

And in some cases, you're including Javascript from a 3rd party provider and you don't really have a choice. Certain ad systems, as well as Google Analytics, spring to mind.

Asteria answered 30/6, 2009 at 15:2 Comment(1)
I always put the Google Analytics code in a separate file, I don´t see any reason not to.Cairistiona
C
2

If the script must be dynamically generated (say by a PHP or ASP.NET MVC page) would be one reason to have it inline :-)

Cycloparaffin answered 30/6, 2009 at 15:3 Comment(3)
Just set an extension like .phpjs up on your server to be processed by PHP and served as text/javascript. Or even just get PHP to process .js full stop if performance is not a worry.Enochenol
Even still, it is far better to have a separate php file with the proper headers (and, for that matter, there are ways to make php read .js files for PHP code). There are very few times when JavaScript has to actually be present on the page and most of these can be avoided if things are written with that in mind.Dutyfree
If there's a situation that needs dynamically generated JavaScript, I would consider using Ajax instead.Hephzipah
G
2

Depends on how much JS do you plan to write. If you're writing many support routines (lots of validation checks, text processing, animation and effects) then it makes sense to have the code in a separate file. This allows code reuse and removes a lot of junk from your HTML page.

On the other hand, there is no need to put 10 lines of code, or a single function (a refresh JS comes to mind) in a separate file. It will also load slightly faster, since the browser does not need to make an additional HTTP request to download the separate JS file.

Geocentric answered 30/6, 2009 at 15:6 Comment(1)
If it's required on many pages, that benefit soon cancels out from redownloading every time. While if it's one file, it can be cached.Enochenol
B
0

Most XSS vulnerabilities can only be exploited using inline javascript.

Beauteous answered 30/6, 2009 at 15:4 Comment(0)
L
0

It's not necessarily enough of a reason, but the pages will load faster. To this end, sometimes, even when you write the script in another file, you want it to show up as inline on the client side.

Lavabo answered 30/6, 2009 at 15:5 Comment(2)
If it's required on many pages, that benefit soon cancels out from redownloading every time. While if it's one file, it can be cached. Compared to the benefit of caching, inlining is minimal.Enochenol
Generally only page specific things would ever be inlined, but also, it really depends on the netlag vs. throughput for your site. Since most browsers do check if a file is newer on request, there is still a slight hit when you don't inline. I mostly don't use inlining, I'm just saying.Lavabo
C
0

I sometimes place javascript inline in pages that get partially reloaded (to bind some events to newly added form-fields for example) and / or pages that use some unique javascript that I will not use on any other page.

Cairistiona answered 30/6, 2009 at 15:8 Comment(0)
O
0

Having many external scripts can ultimately slow down the page as the browser must call each file separately. Combining the JavaScript into one file or into the page itself can sometimes alleviate this problem.

On the other hand, I believe the browser may cache a script file once it's been called for the first time so if you have a lot of the same code across your site, external is the way to go.

Omaromara answered 30/6, 2009 at 15:21 Comment(1)
I like your idea about having everything load into one page. You could combine a couple of ideas already mentioned to do this. For example, create all of the JavaScript files in several different .js files, and then use PHP's include_once to load them all into one page. Thus, you have the benefit of having multiple .js files to edit, but you also have the benefit of only one page for browsers to read.Dutyfree
D
0

I work a good deal in something called Flex, which combines XML and ActionScript to create the final bytecode. It is ALWAYS best practice to separate the two as much as possible. That way, you can very clearly and easily separate the View (the HTML or MXML in my case) from the Controller (the script)

It also means that you do not have to worry about looking through five files for one line of code -- all of your code is in one place.

Dutyfree answered 30/6, 2009 at 15:24 Comment(0)
S
0

File caching is the reason to have external js and css files. Even if you only have one HTML page, this page is likely to be updated often and so will be downloaded by the browser as often. If the js (and css) are in the HTML page, that too will be downloaded often. Keeping them separate will keep the HTML file smaller and will download faster. The js and css files will have been cached so will not be continually downloaded. That is assuming these files are not updated very often.

Strand answered 17/4, 2022 at 8:26 Comment(0)
G
0

There are common situations where inline javascript is the developer's only option. For example, when customizing certain CMS systems.

While most users of SO would never touch a CMS (excepting those who drank the WordPress koolaid), many of our friends and relatives reach for the low-hanging fruit and end up on Wix or Shopify or (God help us) Nationbuilder.

In some of these CMS environments you have only limited access to the underlying code.

I was assisting a family member last night on Shopify and we spent over an hour looking for how to create a simple show/hide-on-click functionality on a template she had customized. After an hour, we could only see how to directly edit the isolated HTML for the elements themselves, individually. What worked was to add an id attribute to the desired element, and then write inline-javascript (i.e. actually using the onclick attribute for the element itself) on the triggering elements.

That worked. First time in my life that I've ever had to use/write inline javascript. So... there you have one real-world necessity.

Perhaps after more hours of sleuthing we might have found "the right way" to do that in Shopify, if there is a better way, but we got it working and were able to call it a night. And I thanked God for inline javascript.

Gigot answered 29/11, 2023 at 14:32 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.