I just like to ask what the title says. The following string required into HTML script tags?
<!--
//-->
If I don't use them what would happen?
Not unless you are targeting browsers that predate the <script> element (i.e. Netscape 1 and friends). (Hint: You aren't).
If you don't use them, and a browser that old (so old it can't even cope with the HTTP Host header which is needed for sites that use virtual hosts) tries to access the site, then the content of the <script> element will be treated as text to be displayed.
Further reading: Comments and CDATA: The mysterious history of script and style in HTML
The worse thing that can happen is that your page is retrieved by a user agent that's not aware of the <script> tag and tries to parse your script block as regular HTML. JavaScript code will be handled as regular text and < symbols might interfere with the page markup. A forced example:
<script type="text/javascript">
if(a<del || a>b){
foo();
}
</script>
Lorem ipsum dolor sit amet.
... could render as ugly deleted text:
if(ab){ foo(); } Lorem ipsum dolor sit amet.
Do these obsolete user agents exists? Oh, sure they do. Please note I've carefully avoided the word "browser". The question is not who's using Mosaic nowadays. It's that a your site can be read by a poorly-written PHP-powered regexp based parser.
Should you care? Well, probably not :)
If you don't use them, a browser from the early 90's might display the source JS code instead of running it.
No, they're not required.
This habit is required for supporting really old browsers and is slightly related to including CDATA tags which should be included for validation purposes. Neither of them are required, but serve or have served their purpose as is clear from some of the more elaborate answers.
See: When is a CDATA section necessary within a script tag?
For valid HTML, your inline JavaScript should be HTML escaped.
If you were to write a script such as:
<script type="text/javascript">
document.write('<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>');
</script>
There will be an issue, because the script contains </script> which will close the first opening script tag. Older user agents had all sorts of issues with poorly escaped JavaScript, and it was easier to tell people to use:
<script>
//<!--
//-->
</script>
Than it was to teach people to write the script as:
<script type="text/javascript">
document.write('<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>');
</script>
Note that JS comments are used to prevent the JavaScript engine from trying to execute <!-- and -->, which might be legitimate statements (a<!--b and a-->b).
Than explain that they actually needed to turn every " to ", < to <, > to > and & to &.
The "modern" fix for this is to use a character data element, which tells the document that everything contained should be treated as literal text:
<script type="text/javascript">
/* <![CDATA[ */
/* ]] */
</script>
In this case I'm using multi-line comments so that the code isn't corrupted if it's minified to a single line (some rich text editors have done this to me in the past).
The best solution is to simply keep all HTML in .html files, all CSS in .css files and all JS in .js files. You won't ever have to worry about HTML escaping your JavaScript, and you'll be able to reuse your JS elsewhere simply by inserting a new <script>.
Google "why comment out javascript in html", first hit:
http://www.howtocreate.co.uk/tutorials/javascript/incorporate
This is not needed any more. All current browsers are aware of script tags, and how to treat their contents, since they have been part of HTML since HTML 3. Browsers that do not understand HTML 3 or scripts (these are virtually never used now) will display the script as if it was the content of the page. You can hide the script from them by commenting out your script with standard HTML comments.
99% of the time, they are no longer needed :) Unless your running some really old browser!
Commenting JavaScript code in such way may also prevents the content from indexing in search engines and may be desirable in some cases.
For example, some time ago I found a lot of "page not found" issues in the Google webmaster tools. After simple analyzing of the urls, I cleared out that Google get all path-like variables from my JS code (like "name/001"), joined them with the current url (mysite.info/staff) and tried to request the resulted url. Without success, of course.
After inserting <!-- //--> in some of JS blocks, all "page not found" issues disappeared in a matter of month or two.
Related
This might be a silly question but i want to clarify this. what happens when we close a javascript two times.
<script type="text/javascript">
alert("hello");
</script>
</script>
i did this but am not getting any error.its like we closed the script so there wont be any execution so no error will trigger i believe. will this create trouble under any situation?
why am asking this is i would like to insert a </script> at the end of a plugin where user submits their script. So that i don't have to go for extra coding on validation if this works fine without creating any trouble
The browser will treat this as an extra, unexpected end tag. It doesn't matter that it's </script>, it could also be </link> or anything else allowed in the same context.
Most browers will silently ignore such extra tags unless you enable strict / XML mode. For strict mode, you should get errors in the console.
To properly wrap plugins supplied by the user, I suggest this strategy:
Always wrap them in your own tags (so you can be sure the structure is always correct).
Check the string that you put between the two tags for <script, <script> and </script> and report an error if you find any of them.
The idea here is that users should never use script tags in their code and that you put them where they belong.
Most browsers will just remove/ignore an extra tag. I can't see that it's would cause any problems, but it is quite an ugly way to do it. I have no better suggestion currently though.
nothing. the browser ignores it but it will obviously not pass standards.
as far as i know, if the browser comes across an opening <script> tag, it assumes everything until the closing </script> tag is script. so starting with a </script> will have no effect but to cause an 'unexpected` exception.
The effect may change depending on the browser, but in teory all ignore the second tag.
XHTML rules are much stricter than those of HTML. When special XML
characters (such as & and <) are used in scripts in XHTML files, they
cause errors. The simplest workaround is to use external script files.
However, if you simply must write inline scripts, then you will need
to include CDATA (character data) sections in your file. Within CDATA
sections the special XML characters can be used freely. The following
example uses a CDATA section that is compatible with both XHTML and
HTML syntax.
<script type="text/javascript">
//<![CDATA[
alert((1 < 2) && (3 > 2));
//]]>
</script>
Also it is not a correct practice and if the script is inline than it will break W3C compliance.
To answer your direct question: Nothing would happen, it's just invalid (x)HTML which the browser ignores.
To answer your indirect question, turned out in the comments:
#DanFromGermany So you are saying validation is the only way there otherwise this way is not recomended
Validation of external resources is always critical.
For example, simply reading external scripts into <script></script> tags, tells the browser "this is no external content" and hereby grants more access, for example, read your cookies and set cookies originating from your domain (external content....your domain).
Including external JS via <script src="...">, from a different host/domain, tells the browser "this is a 3rd party script, don't allow it as much as internal scripts." It is therefore not allowed to read or set your cookies and stuff.
Why putting in </script> does not help:
An attacker is easily able to screw your whole website and let it easily disappear.
See the following:
<script>
<!-- external script start -->
</script>
</head>
<body>
Attackers website start
<div style="display:hidden;">
everything below disappears
<!--
<!-- external script end -->
</script>
</head>
<body>
<!-- your website start !-->
Still if you prevent this, an attacker can always use document.write(); to insert HTML into your Website.
Probably the best way is to executed the given JS through an iframe, from a blank page and an independent (sub)domain.
Putting things into database, or save ones JS and let it execute by a different user needs additional validation.
Now that the type attribute of the <script> tag can be omitted in HTML5, is this the fewest number of characters required to include external JavaScript on a page?
<script src="URL"></script>
Can anyone optimise it any more than this - what about if a framework such as jQuery was already loaded, is there an even shorter way?
You could omit the quotes for the attribute:
<script src=URL></script>
As well, with XHTML5 the following should work:
<script src="URL" />
If you don't care about the JavaScript being able to reach out and access page content, then
<img src="URL.svg">
where the URL points to an SVG image that uses SVG scripting would allow you to load a script and you could call functions defined in it by sending events to the SVG image to trigger event handlers.
You may be able to get around that restriction by using an SVG served from the same origin but I believe the security consequences of same-origin access for SVG are poorly understood so spec and browser writers are treading cautiously.
Since you asked about jQuery, you can use $.getScript():
$.getScript("f.js");
Of course this assumes your code has already been wrapped, or loaded in via in <script> tags. To be honest, there really isn't much benefit in trying to shave off a few more bytes in this area. It's not like referencing scripts requires a great deal of verbosity anyway.
Keep your code readable, and don't deviate too far from standards and accepted conventions.
[from my comments]
Supposing you already handled script aggregation using for example the excellent Google Closure Compiler and you don't want to use the heavy js loading libraries, a simple optimization is this :
<script src=a></script>
(no quote, no ".js", yes that's silly)
Of course, you can also remove spaces and CR before and after this part.
If I have a userscript that I've found online, and I'd like to incorporate it into a website as a normal javascript (i.e. not userscript), how can I do that?
This seems like it would be something pretty simple but I am new to javascript and userscript, hopefully somebody can help me out.
For example, I found this userscript: "Convert UPS and FedEx Tracking Numbers to Links"...
Which will parse a page for regular expressions matching any UPS/FEDEX/USPS tracking number, and convert them to links to the respective carriers' tracking website to track that number.
This works great as a userscript, but I would like it to be automatic on the site I am working on (not require visitors to download/install a userscript).
How can I use this userscript as a regular javascript?
UserScripts are usually executed after the page DOM is loaded, to make sure that the page contents can be completely accessed. So, you need some kind of mechanism to achieve that. But this is a bit tricky since older versions of IE need special treatment.
Doing it manually would require about 30 lines of code. Libraries like jQuery offer a ready() method like so:
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function () {
// put userScript here
});
</script>
It should just be a matter of linking it like any other Javascript file:
Save it as foo.js, then in your html,
<body>
<!-- body code here -->
<script src="foo.js"></script>
</body>
You can just put it in a JS file and include the file in your page.
UserScripts contain normal Javascript code, but are executed by a plugin rather than being on the page.
Why are some JavaScripts encapsulated within these tags:
<!--//--><![CDATA[//><!--
some js here
//--><!]]>
<![CDATA[//> is to prevent XML parsers from choking on the script.
<!-- ... --> is not required unless you're using Netscape 1.0.
See: Does it still make sense to use HTML comments on blocks of JavaScript?
It makes it valid XHTML.
They were used for old browsers which didn't understand the <script> tag. That way if a browser didn't properly read the JavaScript, it would just render it as a comment and not show up on the page.
It also allows JavaScript code to be inside valid XHTML pages without having to escape characters which aren't valid in XML.
I'm not sure about what's the difference between opening a JS script with
<SCRIPT language='JavaScript'>
or with:
<SCRIPT type="text/JavaScript">
Should JavaScript always be quoted (either with " " or with ' ') or that's not really important?
Thank you for any clarification on this topic!
The language attribute was used in HTML 3.2. HTML 4.0 introduced type (which is consistent with other elements that refer to external media, such as <style>) and made it required. It also deprecated language.
Use type. Do not use language.
In HTML (and XHTML), there is no difference between attribute values delimited using single or double quotes (except that you can't use the character used to delimit the value inside the value without representing it with an entity).
Refer to supreme deity Douglas Crockford's Javascript Code Conventions for all things Javascript:
JavaScript Files
JavaScript programs should be stored
in and delivered as .js files.
JavaScript code should not be embedded
in HTML files unless the code is
specific to a single session. Code in
HTML adds significantly to pageweight
with no opportunity for mitigation by
caching and compression.
<script src=filename.js> tags should
be placed as late in the body as
possible. This reduces the effects of
delays imposed by script loading on
other page components. There is no
need to use the language or type
attributes. It is the server, not the
script tag, that determines the MIME
type.
Older browsers only support language - now the type method using a mimetype of text/javascript is the correct way.
<script language="javascript" type="text/javascript">
is used to support older browsers as well as using the correct way.
<style type="text/css">
is another example of including something (stylesheet) using the correct standard.
You don't need the type and language attribute when using to an external JavaScript file:
<script src="script.js" />
Your browser will automatically figure out what to do, based on the extension of the file. You need type="text/javascript" when doing script-blocks, though.
Edit:
Some might say that this is awful, but these are in fact the words of a Yahoo! JavaScript evangelist (I think it was Douglas Crockford) in the context of website load-performance.
Perhaps I should have elaborated a bit.
Google was a great example of breaking standards without breaking the rendering of their website. (They are now complying to W3C standards, using JavaScript to render their pages). Because of the heavy load on their websites, they decided to strip down their markup to the bare minimum, and use depreciated tags like the dreaded font and i tags.
It doesn't hurt to be pragmatic. Within reason, of course :)
According to the W3 HTML 4.01 reference, only type attribute is required. The langage attribute is not part of the reference, but I think it comes from earlier days, when Microsoft fought against Netscape.
Also, simple quotes are not valid in XHTML 1.0 (the parsing is more restrictive).
This may not be a problem but you should now that's always better to validate your html (either HTML 4.01 or XHTML 1.0).
Use both:
<script language="javascript" type="text/javascript">
You should always enclose attribute values in quotation marks ("). Don't use apostraphes (').
Edit: Made opinion sound like fact here, my bad. Single quotes are technically legal, but in my experience they tend to lead to more issues than double quotes (they tend to crop up in attribute values more often amongst other things) so I always recommend sticking to the latter. Your mileage may vary though!