HTML5 <script> declarations - javascript

Is it still necessary (or even good practice) when using HTML5 to declare the script type when using a script block?
e.g. <script type="text/javascript">
Plus what about using a CDATA block in the script for browser parsing?
e.g. // <![CDATA[ ... ~code here ~... // ]]>
Any help much appreciated.

The current draft of HTML5 doesn't require the type attribute for script tags.
Also the <![CDATA is not required in HTML5 (it was XHTML specific anyway).

Is it still necessary (or even good practice) when using HTML5 to declare the script type when using a script block?
HTML 5 defines text/javascript as the default, and you'd be hard pressed to find a browser that didn't treat it as such. So you can omit it.
Plus what about using a CDATA block in the script for browser parsing?
Pointless unless you are writing XHTML 5 and using characters such as < or & in the script (but you should almost always be using external scripts anyway).

The CDATA comments are for XML, so only applicable if you're serving your pages up as xml (which you shouldn't be if it's HTML5).
As for the type attribute, it's optional now in HTML5.

Related

What difference does having attributes in the <script> tag make compared with no attributes? [duplicate]

I read somewhere that you no longer need things like type="text/javascript" and the weird CDATA and <!-- things in your script tags. So, instead of:
<script type="text/javascript">
//<![CDATA[
<!--
//your script here
-->
//]]>
</script>
You would just do:
<script>
//your script here
</script>
I can't remember where I read this though. It was from a Google or Yahoo engineer I think, and they specifically mentioned which browsers required these archaic constructs and why. Anyone know what blog post/article this was talked about, or have a good resource talking about this?
See Crockford's write-up on the <script> tag, most notably:
Do not use the <!-- //--> hack with scripts. It was intended to prevent scripts from showing up as text on the first generation browsers Netscape 1 and Mosaic. It has not been necessary for many years. <!-- //--> is supposed to signal an HTML comment. Comments should be ignored, not compiled and executed. Also, HTML comments are not to include --, so a script that decrements has an HTML error.
...
type="text/javascript"
This attribute is optional. Since Netscape 2, the default programming language in all browsers has been JavaScript. In XHTML, this attribute is required and unnecessary. In HTML, it is better to leave it out. The browser knows what to do.
It's a Crockford recommendation. I know I've seen it echoed elsewhere (ppk maybe?). The HTML5 spec does not require it.
Oddly, it's become somewhat au courant to use the "type" attribute to mark <script> blocks that you don't want to be evaluated:
<script type='text/html-template'>
<div> this is a template </div>
</script>
By giving a weird non-JavaScript type, you get a way to stuff raw text into the page for use by other JavaScript code (which is presumably in script block that can be evaluated).
HTML5 doesn't need the type="text/javascript" (it's the default).
CDATA is only neeed for XHTML pages, if the script has any HTML characters (like '<' and '>') in it.
<!-- should only be needed for OLD browsers.
The type attribute identifies the scripting language of code embedded within a script element or referenced via the element’s src attribute. This is specified as a MIME type; examples of supported MIME types include text/javascript, text/ecmascript, application/javascript, and application/ecmascript.
According to HTML 4.01 Specification
The type attribute specifies the scripting language of the element's
contents and overrides the default scripting language. The scripting
language is specified as a content type (e.g., "text/javascript").
Authors must supply a value for this attribute. There is no default
value for this attribute.
But in HTML5 text/javascript is the default type, so you can omit
The type attribute gives the language of the script or format of the
data. If the attribute is present, its value must be a valid MIME
type. The charset parameter must not be specified. The default, which
is used if the attribute is absent, is "text/javascript".
Well, I am tempted to say that nobody is using text/javascript any more, and that even minification tools would probably remove it...
Indeed, Facebook SDK documentation specifies just <script>.
However,
Google SDK documentation still has text/javascript.
Amazon SDK documentation still has text/javascript.
Linkedin API documentation still has text/javascript.
Instagram is still using text/javascript.
you may be thinking of this article here with the dependency being that scripts default to text/javascript in HTML5 automatically, while non-HTML5 browsers still expect that you define the type specifically spec-wise even though they will almost always guess text/javascript anyways.
👉🏻 The HTML5 specification urges authors to omit the attribute rather than provide a redundant MIME type. MDN
The MIME Sniffing Standard lets JavaScript be served using any MIME type (Multipurpose Internet Mail Extensions) that matches the following:
<script type="application/javascript"></script>
<script type="application/ecmascript"></script>
<script type="text/javascript"></script>
<script type="text/ecmascript"></script>
it's up to the browser to interpret the script block correctly based on the headers, i believe, and not the type attribute. So to answer your question, no it is not required for modern browsers (i'm talking IE7+, FF, Webkit). If you are supporting older browsers than that...I feel sorry for you =)
If you're putting a script tag inside SVG you must specify the type attribute. And it should be "text/ecmascript" rather than "text/javascript".
If your script is inline (not linked) you will need to wrap the script body in a CDATA declaration too. The inline script boilerplate for SVG (and other XML variants) is thus
<script type="text/ecmascript">
<![CDATA[
// your javascript code goes here
]]>
</script>
These might be special cases 'in the wild', but they are real enough, and SVG use is growing, so it's incorrect for anyone else to suggest that the type attribute and CDATA are entirely obsolete in modern browsers. The use cases are narrow, yes, but not unheard of.
"Change the environment to its opposite and every piece of wisdom becomes the worst of folly." - Ashby
Well i keep seeing more examples without the text/javascript but for some reason my scripts wont work in FF when i do so. I would recommend keeping the text/javascript declaration. The CDATA tag prevents javascript from being shown as plain text in your website if your browser has javascript turned off. Personally i don't use those tags anymore don't think there's allot of users out there without and if they are out there they might wanna grow some brains :P
type="text/javascript" : Required in HTML 4 and XHTML, but optional in HTML5.
CDATA : Required in XHTML.
<!-- : Used to hide the JavaScript from very old browsers. Eg: Netscape 1 and Internet Explorer 2, neither of which anyone uses any more.

Why does a self-closed script tag not trigger errors?

The following code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>A</title>
<script type="text/javascript" src="./script.js" />
<script type="text/javascript">alert("This is skipped.");</script>
</head>
<body>
</body>
</html>
passes the validation test at W3C and Chrome does not display any Javascript errors on this page. However, the entire text <script type="text/javascript">alert("This is skipped."); is not parsed by the Javascript engine which just looks for the </script> tag even though it's self-closed. The file "script.js" is loaded, however.
In Chrome, Firefox and IE 11, this leads to this same behaviour.
Why is this? What is actually happening here?
The code you have is valid because you have an XHTML doctype. In XHTML any element is permitted to use the self-closing syntax (although it makes little sense for most of them).
If you were serving your document with an XML content type (Content-Type: application/xhtml+xml for example) then it would work in browsers too.
Since you are (presumably) serving the document with Content-Type: text/html, the browser will parse it as HTML.
The first script tag will be parsed (the / will be ignored or treated as an invalid attribute).
The second script tag will be parsed by the HTML parser as JavaScript (so it will be treated as text)
The first script end tag will be parsed (and close the script tag from (1))
Since the first script tag has a src attribute, the external script will be loaded and passed to the JS parser
The inline "JavaScript" (the second script tag) won't be passed to the JS parser because a script element can't have an external and inline script (so you won't get a JS error from it). It may be added, as text, to the DOM though.
Note that the use of the self-closing syntax for script elements is banned by appendix C because HTML parsers do not give the desired result. All in all, XHTML is far more trouble then it is worth 99%+ of the time, and you should stick to using HTML instead of XHTML.
The script element is generally used in two ways, to either contain code between the two tags of the script element or to include code. When it includes code it does not technically need the end tag for the script element.
The quickest way to test the code as actual XHTML (application/xhtml+xml) is to create a file with a .xhtml file extension and then open that file in Firefox. Gecko, unlike the two Webkit forks (Chrome and Safari) and Trident (IE) will actually break the page and instead show an XML parsing error message, other rendering engines will simply stop rendering at the point the XML parse error was encountered.
A few things about correctly handling script elements...
There is no such mime as "text/javascript", it's actually application/javascript.
Microsoft's IE doesn't understand JavaScript until IE9 and will simply not render JavaScript unless it's served with this non-existent weird mime "text/javascript". If you're building your own stuff 2014 or onwards simply ignore Internet Explorer 8 and older as their shares will be utterly negligible by the time you bring something to market.
Avoid putting script elements in the body element if you're trying to learn how to code clean and strict, it'll force you to organize things; ensure you use the defer="defer" attribute/value pair if you had been putting script elements in the body for performance reasons.
If you have a lot of scripts simply use a server scripting language like PHP to include() multiple files in a single file. You'll have to use Apache to enable PHP rendering in a *.js file and then you'll need to output the correct mime.
JavaScript Example
<script defer="defer" type="application/javascript">
//<![CDATA[
window.onload = function
{
alert('Hello World.');
}
// ]]>
</script>
Everything that I've mentioned can be seen at my website in my profile as I code as strictly as possible. Sure strict code takes longer though I end up with almost utterly no maintenance which saves me hordes of time in the long run.

Error: Not allowed element when it is in JS

Just a quick validation question, I get:
document type does not allow element "div" here
And my code:
$('#wrapper').prepend('<div id="slider"></div>');
It's just a JS stuff, how do I handle this?
I can't think of any time you would get that error in the middle of a piece of JavaScript unless you are using XHTML, in which case the short answer is: Stop using XHTML, start using HTML 4 or 5.
The reason you get the error is described in the XHTML 1.0 specification:
In XHTML, the script and style elements are declared as having #PCDATA content. As a result, < and & will be treated as the start of markup
The latest version of the XHTML Media Types note provides work–arounds:
DO use external scripts if your script uses < or & or ]]> or --. DO NOT embed a script in a document if it contains any of these characters.
and
If you must embed the content, the following patterns can be used:
<style>/*<![CDATA[*/
...
/*]]>*/</style>
This is all rather a lot of effort, and just switching to HTML is a simpler option. Browsers are designed for HTML and their XHTML support is provided as an afterthought. If you get any benefits from XHTML it will be from using it with server side tools as part of your publishing process … and not many people are doing that.

Please help me figure out what kind of a scripting language is this

I just ran across a html page which has some scripts. The script tag starts with the following line:
<script type="text/IMAN">
my question is what is a IMAN script?
I know javascript usually starts with <script type="text/javascript">
I changed to , now the page shows all the code.
Giving a browser a mime type that it doesn't understand is a great way tell it to ignore your code...allowing you to store code snippets for later - this is most commonly used in templating like https://github.com/janl/mustache.js. Here is how it is used to store content:
<script type="text/template" id="template">
<div>this is my hidden content for a popup</div>
</script>
var content = $('#template').html();
$('#popup').html(content).show();
You can specify any valid MIME type (which basically just means "two identifiers separated by a slash") for the script type and the browser will ignore the content, if it doesn't recognize the type. Likely it's an HTML template or something else that the developer wants to access from Javascript but wants the browser itself to ignore. The IMAN name? Probably some injoke by the programmer.
In jQuery (for example), you could access it like:
$("script[type*=IMAN]").each(function()
{
// Do something with $(this).text() or .html() or whatever
});
It's an invalid MIME type. The "type" attr. in an HTML <script> tag should contain a valid HTML mime-type. Usually its value text/javascript (for a Javascript resource). At any rate, there's no mime-type called text/IMAN.
I know this is an old post, but the tag
<script type='text/IMAN'>
is the start (open tag) for writing imanscript. Imanscript is a proprietary scripting language used by Siemens Teamcenter PLM. The scripting language is sort of like VBscript, but strictly for the web api programming. The original scripting language was originally called imanscript, but in the latest version of Teamcenter it is referred to as tcscript.

Will non-IE browsers use script inside a tag with type="text/jscript"?

I inherited an ancient codebase that includes pages with <script type="text/jscript"> -- yes, my life really does suck that much. The script appears to do nothing in modern, decent browsers (FF and Chrome, for a start) and I'm wondering if the stated script type is causing it to be ignored. I spent some time trying to figure out what's going on, and I see things like
As explained by JavaScript guru Douglas Crockford in his talk entitled The JavaScript Programming Language on YUI Theater, "[Microsoft] did not want to deal with Sun about the trademark issue, and so they called their implementation JScript. A lot of people think that JScript and JavaScript are different but similar languages. That's not the case. They are just different names for the same language, and the reason the names are different was to get around trademark issues."
on Wikipedia. So Javascript == JScript? But then, I see conflicting information, like this answer which seems to suggest that script that's declared as JScript will only run in IE.
So: can I just change the type tag and everything will work fine? Is there a simple process for conversion? If not, I may just scrap the whole thing and start over.
From HTML 5 chapter 4.3
7) If the user agent does not support the scripting language given by the script block's type for this script element, then the user agent must abort these steps at this point. The script is not executed.
That same chapter also says
If either:
the script element has a type attribute and its value is the empty string, or
the script element has no type attribute but it has a language attribute and that attribute's value is the empty string, or
the script element has neither a type attribute nor a language attribute, then
...let the script block's type for this script element be "text/javascript".
so I would just remove type="text/jscript" save a bit on bandwidth and live happily ever after.
So Javascript == JScript?
JScript is what Microsoft calls JavaScript
But then, I see conflicting information, like this answer which seems to suggest that script that's declared as JScript will only run in IE.
That doesn't conflict. It just means that other browsers don't recognise the mime type.
Browsers will ignore script elements with a type they do not recognise. text/jscript is non-standard and most browsers don't recognise it (Internet Explorer considers it an alias for text/javascript).
can I just change the type tag and everything will work fine?
Probably. The script might depend on other proprietary Microsoft—isms (such as document.all) or other non-standard behaviour (automatic id attribute to JS global conversion or treating CSS lengths that are missing a unit as pixels) though.
The other answer you linked to is completely incorrect. There are no differences between JScript and JavaScript. Changing the script type to "text/javascript" should work (unless the intent of the author was to force it so that only IE ran the script)
the type= requirements have been taken out of html5. I believe the proper xhtml code would be ...
<script type="text/javascript">
<![CDATA[
// content of your Javascript goes here
]]>
</script>
... but browsers did not follow the requirements of xhtml of forcing an error. Most web hosts keep the delivery of xhtml and html docs as MIME-type "text/html", not the "application/xhtml+xml" which should force an error if the xhtml does not validate.
HTML4 uses are variety of types ... http://www.w3.org/TR/html4/interact/scripts.html ... but browsers do not force html4 validation.
vscript, tcl don't have common support - we are talking about Javascript or any of the other names it gets as in becomes a more powerful language.
A bogus "type" attribute will definitely make scripts not work. The browser thinks you don't want it to run the script, basically.
Really, the "type" attribute is not necessary unless you definitely don't want the browser to run a script (which people do when their "scripts" are actually template bodies, or other data like that). You could either change all yours to "text/javascript" or just get rid of the attribute entirely.

Categories

Resources