Is placing javascript directly on HTML document deprecated? - javascript

I am shocked to read the following from Quirksmode:
Deprecated: Direct JavaScripts
Do not use direct JavaScripts for the reasons explained in section 2C
of the book. This section is only maintained for historical reasons.
The simplest method is to place your scripts directly in the page. How
to place
<script language="javascript" type="text/javascript">
<!--
script goes here
// -->
</script>
Based on my understanding reading the article, javascripts are to be included using the src attribute on <script> tags instead. I don't have the book and can't find further references online that says this. Does anyone know whether this is correct or did I misinterpret what it is trying to say?

No HTML specification marks inline JavaScript as deprecated or obsolete.
It is widely regarded as being less than best practise though.

PPK means that the section itself is deprecated. The advice presented there was generally accepted and relevant at the time of publication, but it no longer aligns with current markup languages and best practices:
The language attribute has been deprecated since HTML 4.01.
In HTML5, the default value of the type attribute is text/javascript—thus, it can often be discarded.
The HTML comments (<!-- and -->) surrounding the script itself are a workaround for the IE 2 and Netscape 1 generation of browsers, and have not been required for nearly 20 years.
Later he advises that you place scripts in the head of your document. This made sense in the days of dial-up, but nowadays it is recommended that outside of a few specific circumstances (e.g. Modernizr, html5shiv) you should place scripts at the end of your document body to prevent them from blocking rendering and parallel downloads.
More current advice
Avoid inlining scripts in general for better maintainability and cacheability. You are still allowed to inline scripts, and it may make sense if:
the script is dynamically generated for just that page; or
the script is very small, and you can demonstrate a measurable and worthwhile improvement in performance due to avoiding the additional HTTP request.
Unless otherwise necessary, use the following syntax for inline JS.
HTML5:
<script>
// ...
</script>
HTML 4.01:
<script type="text/javascript">
// ...
</script>
XHTML5:
<script>
//<![CDATA[
// ...
//]]>
</script>
XHTML 1.x:
<script type="text/javascript">
//<![CDATA[
// ...
//]]>
</script>

It is not deprecated, and it is still used widely.
If you look at this question: https://softwareengineering.stackexchange.com/questions/86589/why-should-i-avoid-inline-scripting it is very well explained why its a bad idea.
The biggest problem i have with it, is that it makes your html pages look stuffed. If you for example have a bit of javascript inline, and a bit of javascript in another file, it is pretty hard to find the right code if you need to change it.
Same goes for inline css. It makes your html files harder to read and understand.

script tag is not deprecated.
The relevant section is called "Deprecated: Direct JavaScripts", and
the note referes to the section's title. Must read:
"Do not use "Direct JavaScripts" recommendations for tag
syntax. This section is only maintained for historical reasons."
the section is deprecated
http://www.peachpit.com/articles/article.aspx?p=1338952&seqNum=3

Related

Using JS to write a noscript tag

Is there any practical reason why you would write out a <noscript> tag with JavaScript's document.write()? Our ad department has been doing this for years and still does it after I've pointed it out. I'm 99% certain that this is due to an ancient ad template written by someone who didn't know what he was doing and no one has thought to change it because, "why fix what ain't broke?" Or maybe someone is reading their "best practices" wrong ("Always include a alternative for browsers that have JS disabled"). Or maybe there's a really good reason I don't know about.
The only conceivable thing I can think of is that you could use it to modify the DOM without it appearing visible on the page and maybe use that content like a template for later use, but this seems pretty far-fetched.
(edit)
The tag in this case contains a standard <img src="/path/to/image" />. Because this is what the original, non-dynamic ad tag would have looked like, this makes me think this is just copy-pasted garbage.
The other thing I should say is that the reason I'm not 100% sure this is an oversite is because of the recent pattern of putting html templates inside <script type="text/x-my-custom-template">...</script>. I'm sceptical that someone on our end would have come up with this on their own, but it could have been a standard ad practice by someone with unusual cleverness.
Is there any practical reason why you would write out a <noscript> tag with JavaScript's document.write()
Nope. The two (<script> and <noscript>) are mutually exclusive. It's like writing a piece of code like this:
if (true && false) {
// do something important
}
If JavaScript is enabled, the browser ignores the <noscript> tag. On the other hand, if JavaScript is disabled, the <noscript> tag will never be written, because the <script> tag is ignored.
This is used for bot detection / fingerprinting.
For example if I use
document.write('<script src='...'>...</script><noscript><img>....</noscript>');
Chrome 55+ blocks not same origin scripts written from document.write(). This means the above <noscript> actually will run on certain/newer versions of chrome despite coming from a "script".
The assumed purpose is if the bot is pretending to be for example (via spoofing its user agent) a specific version of chrome, and the script is not blocked, it would point to the fact that its not really chrome (bot).
You can add child node in a specific html tags.
var noscript = document.createElement('noscript')
var iframe = document.createElement('iframe')
iframe.setAttribute('src', "<your source>")
iframe.setAttribute("height", "0")
iframe.setAttribute("width", "0")
iframe.setAttribute("style", "display:none;visibility:hidden")
noscript.appendChild(iframe)
document.body.appendChild(noscript)

Custom Tags and Javascript

I am building a web application which is supposed to be (on the development level) highly standardized.
To accomplish this i want to use custom namespace tags which in the sourse code appear as they do, but are modified by javascript depending on what they are.
For example:
<script type="text/javascript">
<!--
alert($('sy\\:icon').attr('location'));
//-->
</script>
<sy:icon id="icon1" location="/path/to/icon"></sy:icon>
Now i have tested this and it does work. What would happen in this example is the entire tag would be replaced by javascript with one or more tags and styles which are valid in html.
My only concern is how different browsers of various versions would respond to an invalid tag, even though it is about to be immediately replaced.
For the record, i am aware that using something like a <div> with a specific class for reference is the normal approach, however using a custom tag would both save space in the source code, and look a lot nicer in my opinion, im just concerned with the implications, if any.
You should declare your custom namespace in the <html> tag as described here. That blog author notes that it's cross-compatible between the various browsers, with IE support back to IE7, so you should be fine.

Mark some Javascript blocks as "special"

For some complicated reason, I need to mark some Javascript as "special", like this:
<script type="text/javascript" someattribute="special">
var special = "I'm special!";
</script>
<script type="text/javascript" someattribute="special" src="special.js">
</script>
Is it possible to do this in way that complies with XHTML standards? According to http://www.w3schools.com/tags/tag_script.asp, all attributes for the script tag have very specific functions. But is there a workaround?
The idea is to pick up the tags as XML elements and put them in anther page, at server level, before it gets to the browser, so I need the special mark in the actual XML of the page. Adding it once the page has loaded, at browser level, using Javascript, will not work.
Any ideas?
Edit:
For the sake of standards-compliance, I can't use HTML5. The whole system I'm trying to be compliant with is XHTML 1.0.
Now that I've had time to think about it, I think that adding a GET variable or an anchor in the src of the script might just do the trick. For example, instead of the previous example, do
<script type="text/javascript" src="special.js?special"></script>
or
<script type="text/javascript" src="special.js#special"></script>
I'll try it now.
If you're using HTML5, you can do this:
<script data-special='true'>
</script>
and it'll validate. However, other than failing validation, you can get away with putting arbitrary attributes on tags and it'll generally work. Using the "data-" HTML5 convention is a safe way to go because you've got a 0% chance of accidentally triggering some weird behavior.
Note that with HTML5 you don't need the "type" attribute, and in fact it's deprecated in trendy Javascript circles.
Use data-* attributes.... They are standards-compliant:
<script data-foo="bar">
With XHTML you are able to create your own DTD and with your own DTD you can easily add an extra attribute to the script tag. However... since you probably want to use this in a real life website this won't work because Internet Explorer does not support that.
So I think these are your choices:
wrap a tag around it to mark it as special (completely standards compliant, works in every browser, but might not work for your check)
adhere to the standards and create your own DTD which will somewhat break IE support
ignore the standards and just add some attribute (noone besides the W3 validator will really care)
If you pick the last option, I suggest using the id attribute. Which, although not supported for script tags, is supported in both html and xhtml in general so browsers won't care too much about it and most validators won't care either.
I'm looking back a this post a long time later. This is just to say that what I wrote in my edit did work and was standards-compliant.

Should I use HTML comments to capsulate JavaScript code blocks?

Some years ago, I was taught that JavaScript code blocks embedded inside HTML should always be capsulated inside HTML comments as following:
<script type="text/javascript">
<!--
var hello = "world";
-->
</script>
I was told to do this, but I never kind of fully figured out why. It kind of seems hacky to use HTML comments, so nowadays I have started using writing my JavaScript code inside the script block without the HTML comments:
<script type="text/javascript">
var hello = "world";
</script>
So my question is: should I use HTML comments to capsulate JavaScript code blocks? Is it safe to just write the script without the comments? I mean am I risking something when I leave out the comment tags?
The HTML comment was intended to hide the JavaScript from ancient browsers that didn't understand the <script> element and instead render its contents on the page. That was way back in the mid-90es, iirc. Nowadays you can safely assume that browsers from that era are no longer present on the web and omit the comments.
Some nice history on that can be found here:
The general rule regarding HTML tags that browsers do not understand is that the browser should ignore the tag completely and treat the content of the page as if that tag were not there. This means that when Netscape 2 first introduced JavaScript (or LiveScript as it was called then), it was necessary to place an HTML comment around the actual script in order to hide the code from other browsers that didn't understand the script tag and which therefore would have displayed the code rather than running it.
The JavaScript language was specifically written to accept the start of an HTML comment as the very first thing in the script and to ignore it in order that the HTML comment could be used to hide the script from people using Netscape 1, Mozaic, Internet Explorer 1, Internet Explorer 2, and other browsers of similar vintage none of which anyone uses any more. It is these prehistoric browsers (in JavaScript terms) that are meant when you see references in antiquated JavaScript tutorials to wrapping your JavaScript inside an HTML comment in order to hide it from "older" browsers.
With Internet Explorer 3, Microsoft introduced their own equivalent to JavaScript which they call JScript. Since then all browsers have at least recognised the script tag and more modern browsers (Netscape 2+, IE3+ etc) the HTML comment is no longer required.So once all your visitors have upgraded to use either Netscape 2, Internet Explorer 3, or a more recent browser than either of those two the commenting out of the script becomes redundant code.
Straight from the source
18.3.2 Hiding script data from user agents
User agents that don't recognize the SCRIPT element will likely render that element's contents as text. Some scripting engines, including those for languages JavaScript, VBScript, and Tcl allow the script statements to be enclosed in an SGML comment. User agents that don't recognize the SCRIPT element will thus ignore the comment while smart scripting engines will understand that the script in comments should be executed.
Another solution to the problem is to keep scripts in external documents and refer to them with the src attribute.
Commenting scripts in JavaScript
The JavaScript engine allows the string "<!--" to occur at the start of a SCRIPT element, and ignores further characters until the end of the line. JavaScript interprets "//" as starting a comment extending to the end of the current line. This is needed to hide the string "-->" from the JavaScript parser.
<SCRIPT type="text/javascript">
<!-- to hide script contents from old browsers
function square(i) {
document.write("The call passed ", i ," to the function.","<BR>")
return i * i
}
document.write("The function returned ",square(5),".")
// end hiding contents from old browsers -->
</SCRIPT>
Furthermore, if you really want to understand what all of this means, read this excellent article. It's lengthy, but worth it.

Are HTML comments inside script tags a best practice? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
The following practice is fairly commonplace in the inline JavaScript I have to work with:
<script type="text/javascript">
<!--
// Code goes here
//-->
</script>
I know that the point is to prevent browsers that are incompatible with JavaScript from rendering the source, but is this still a best practice today? The vast majority of browsers used today can interpret JavaScript; even modern mobile devices usually don't have trouble.
As for the 'why not?' question: I recently had to spend several hours debugging an issue where someone had left off the '//' in front of a '-->' at the end of a script tag buried deep in some pages, and this was causing mysterious JavaScript errors.
What do you do? Is this still considered a 'best practice?'
The important thing is that nowadays, whether a particular browser supports JavaScript or not is irrelevant (clearly the great majority do) - it is irrelevant because almost all understand script blocks, which means that they know to ignore the JavaScript even if they can't interpret it.
Matt Kruse gives a slightly more detailed explanation on his JavaScript Toolbox site for why specifically not to use HTML comments within script blocks.
Quoted from that page:
Don't Use HTML Comments In Script Blocks
In the ancient days of javascript (1995), some browsers like Netscape 1.0 didn't have any support or knowledge of the script tag. So when javascript was first released, a technique was needed to hide the code from older browsers so they wouldn't show it as text in the page. The 'hack' was to use HTML comments within the script block to hide the code.
Using HTML Comments In Script Is Bad
// DON'T do this! Code is just representative on how things were done
<script language="javascript">
<!--
// code here
//-->
</script>
No browsers in common use today are ignorant of the <script> tag, so hiding of javascript source is no longer necessary. In fact, it can be considered harmful for the following reasons:
Within XHTML documents, the source will actually be hidden from all browsers and rendered useless
-- is not allowed within HTML comments, so any decrement operations in script are invalid
I've stopped doing it. At some point you just have to let go of your NCSA Mosaic.
As per W3C Recommendation it was mainly useful to hide the script data from USER AGENTS.
Quoted from the W3c page :
Commenting scripts in JavaScript The JavaScript engine allows the string "<!--" to occur at the start of a SCRIPT element, and ignores further characters until the end of the line. JavaScript interprets "//" as starting a comment extending to the end of the current line. This is needed to hide the string "-->" from the JavaScript parser.
<SCRIPT type="text/javascript">
<!-- to hide script contents from old browsers
function square(i) {
document.write("The call passed ", i ," to the function.","<BR>")
return i * i
}
document.write("The function returned ",square(5),".")
// end hiding contents from old browsers -->
</SCRIPT>
No, it is a hangover from a workaround used when the script element was first introduced. No browser fails to understand the script element today (even if it understands it as "Script that should be ignored because scripting is turned off or unsupported").
In XHTML, they are actively harmful.
I wrote something about the history of it a while back.
Stopped using this a while back. Also, according to Douglas Crockford, you can drop the type attribute from your script tags since the only scripting language available in most browsers is JavaScript.
I would recommend using a CDATA section, as described in this question.
If you are typing manually, I suggest you always use external js files, that would help so much.
Regarding your concern: most browsers are JavaScript safe today. However sometimes people may write simple parsers to fetch a HTML directly - and I must say, the safe quote is really helpful for those clients. Also some non-JS clients like old Lynx would get benefits from this.
If you do not include literal text between script tags- that is, if you load scripts from src files, you can forget about the comments.
I stopped doing that ages ago. You really don't need it in this day and age.
I don't do it but the other day I went to validate my password protected site at w3c. So I had to use their direct input method. It complained about my javascript, so I put the comments back in everything was fine.

Categories