Can't run JavaScript in CDATA - javascript

I am trying to run following HTML in every browser: Opera, FF, IE, Chrome
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="application/xhtml+xml; charset=utf-8">
</head>
<body>
<script>
<![CDATA[
alert('Hey!');
]]>
</script>
</body>
</html>
None of them display the alert. Chrome logs an error in console: Uncaught SyntaxError: Unexpected token <. It seems to be complaining about the fist < in CDATA declaration. Firefox also logs "syntax error"
The w3schools point out that this is the way to use CDATA http://www.w3schools.com/xml/xml_cdata.asp. Other answers on this site suggest it. What am I doing wrong? I tried playing with namespaces and doctypes, but that did not change anything.
Edit: I added XHTML name space and doctype, that I originally removed and the problem still persists.

The difference is between HTML and XHTML. W3Schools is correct that it’s a valid CDATA construct within XHTML, but as your question indicates that your code is HTML and there is no such thing as CDATA inside a <script> in HTML, your example fails as soon as the interpreter sees the "<". You can tell the browser that it’s looking at XHTML, but it's probably safer to handle HTML, too. To do that, you need to hide the CDATA inside JavaScript comments. (You might also consider identifying which language is inside your <script> block.)
<html>
<head>
</head>
<body>
<script>
//<![CDATA[
alert('Hey!');
//]]>
</script>
</body>
</html>
This is, in fact, the method recommended by the World Wide Web Consortium (W3C) in XHTML Media Types, A.4. Embedded Style Sheets and Scripts.

The related question When is a CDATA section necessary within a script tag? explains that a CDATA section is recommended when embedding scripts in XHTML documents. However, just setting a XHTML doctype to the test document isn't enough. The CDATA is still being treated as a syntax error.
According to this blog post, that is because the content type needs to match the doctype definition. Proper XHTML needs to have the following Content-type header set:
Content-type: application/xhtml+xml
if that is not specified and text/html sent instead, browsers will revert to HTML. And indeed, if I add that header to my test case, browsers start properly parsing the JavaScript inside the CDATA even when the CDATA it's not commented out.
This works for me (setting the header using PHP):
<?php header("Content-type: application/xhtml+xml");
echo '<?xml version="1.0" encoding="UTF-8"?>'; ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<script><![CDATA[alert('Hey!');]]></script>
</head>
<body>
</body>
</html>​

You may see it as XML (XHTML) but that's not how the browser sees it.
You're serving it a text/html which means that the browser sees it as HTML.
It needs to be served with an XML mime type such as application/xhtml+xml
i.e. like this
http://www.alohci.net/application/xhtml+xml/starov.htm.ashx
and not like this
http://www.alohci.net/text/html/starov.htm.ashx
Check the view source to see that it's the same file. Check the "Net" tab in firebug (or the equivalent for your browser) to see the content type in the response headers.

Also, you need to comment out the CDATA so it won't throw a parsing error when it's run:
<script>
//<![CDATA[
alert('Hey!');
//]]>
</script>

1) Comment your CDATA
//<![CDATA[
alert('Hey!');
//]]>
2) add a script type
<script type="text/javascript">

Related

Strange CDATA behavior in XHTML with JavaScript

i'm using blogger and i want to make my own template from scratch so i began to understand the very basic structure of how things are.
In my journey through this i encounter the CDATA thing
And i wanted to test this code.
<html>
<head>
<b:skin>
<![CDATA[ ]]>
</b:skin>
</head>
<body>
<b:section id='post'/>
<script>
if(true&&true)
alert("hello");
</script>
</body>
</html>
It gives me an error and i know that the "&" should be "&" instead because it's xhtml so i add the cdata my code will become like this
<html>
<head>
<b:skin>
<![CDATA[ ]]>
</b:skin>
</head>
<body>
<b:section id='post'/>
<script>
<![CDATA[
if(true&&true)
alert("hello");
]]>
</script>
</body>
</html>
Now that i test it the alert message wouldn't show up so i put // before the opening and closing CDATA tag and it works.
I want to understand why the reason it works with // and not without.
Blogger parses the XML templates as XML, so they need to be valid XML to work with Blogger's backend.
However, when Blogger serves the resulting page to the browser it says that the Content-Type is text/html; charset=UTF-8 (which is wrong, because it is XHTML (but see below)).
HTML and XHTML are different languages so when the browser parses the XHTML as HTML it doesn't do anything special with <![CDATA[ and just passes it to the JavaScript engine.
<![CDATA[ isn't valid JavaScript, so this throws an exception.
By prefixing it //, you change the invalid JavaScript into a valid JavaScript line comment.
aside: XHTML and HTML are similar enough that you can get away with pretending your XHTML is HTML if you follow the compatibility guidelines.

without type='text/javascript' is okay for ie9? [duplicate]

<script type="text/javascript">
/* ... */
</script>
vs.
<script language="Javascript">
/* ... */
</script>
Which should be used and why?
Or, the third alternative: omitting either of these, such as the example code in jQuery's API reference:
<script src="http://code.jquery.com/jquery-latest.js"></script>
The language attribute has been deprecated for a long time, and should not be used.
When W3C was working on HTML5, they discovered all browsers have "text/javascript" as the default script type, so they standardized it to be the default value. Hence, you don't need type either.
For pages in XHTML 1.0 or HTML 4.01 omitting type is considered invalid. Try validating the following:
<!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" xml:lang="en" lang="en">
<head>
<script src="http://example.com/test.js"></script>
</head>
<body/>
</html>
You will be informed of the following error:
Line 4, Column 41: required attribute "type" not specified
So if you're a fan of standards, use it. It should have no practical effect, but, when in doubt, may as well go by the spec.
HTML4/XHTML1 requires
<script type="...">...</script>
HTML5 faces the fact that there is only one scripting language on the web, and allows
<script>...</script>
The latter works in any browser that supports scripting (NN2+).
The type attribute is used to define the MIME type within the HTML document. Depending on what DOCTYPE you use, the type value is required in order to validate the HTML document.
The language attribute lets the browser know what language you are using (Javascript vs. VBScript) but is not necessarily essential and, IIRC, has been deprecated.

JavaScript Failure

I try to learn how to write Javascript but I have found a problem either so basic I would never think about it or so complicated that I lack the knowladge to find it.
I am Using NetbeansIDE 8.0 .
<?xml version='1.0' encoding='UTF-8' ?>
<!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"
xmlns:h="http://xmlns.jcp.org/jsf/html">
<head>
<title>Objekt Navigator</title>
</head>
<body>
Something<br/>
<script language="javascript" type="text/javascript">
document.write("Text");
alert("Bla bla");
</script>
Else<br/>
</body>
</html>
If the compiled page is opened it will only display "Something" and "Else" but nothing of the script.
If I remove "document.write("Text");" it will show the alert but there is no wrong wording in "document.write".
I really need one (or more) pointers to understand this.
Pointer 1:
Don't use document.write. Really. It has been archaic and obsolete for at least 15 years, if not 20. Use regular DOM methods.
Whatever tutorial you found that in, choose something else.
Pointer 2: Don't use XHTML. Use the HTML5 Doctype. The XHTML one does some very weird things with JavaScript -- IF the file is being served as XHTML.
Lastly: your code works just fine for me. If this is not the exact code that you are using in your tests, look at your console.log to see if you have an error somewhere.

HTML Script tag: type or language (or omit both)?

<script type="text/javascript">
/* ... */
</script>
vs.
<script language="Javascript">
/* ... */
</script>
Which should be used and why?
Or, the third alternative: omitting either of these, such as the example code in jQuery's API reference:
<script src="http://code.jquery.com/jquery-latest.js"></script>
The language attribute has been deprecated for a long time, and should not be used.
When W3C was working on HTML5, they discovered all browsers have "text/javascript" as the default script type, so they standardized it to be the default value. Hence, you don't need type either.
For pages in XHTML 1.0 or HTML 4.01 omitting type is considered invalid. Try validating the following:
<!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" xml:lang="en" lang="en">
<head>
<script src="http://example.com/test.js"></script>
</head>
<body/>
</html>
You will be informed of the following error:
Line 4, Column 41: required attribute "type" not specified
So if you're a fan of standards, use it. It should have no practical effect, but, when in doubt, may as well go by the spec.
HTML4/XHTML1 requires
<script type="...">...</script>
HTML5 faces the fact that there is only one scripting language on the web, and allows
<script>...</script>
The latter works in any browser that supports scripting (NN2+).
The type attribute is used to define the MIME type within the HTML document. Depending on what DOCTYPE you use, the type value is required in order to validate the HTML document.
The language attribute lets the browser know what language you are using (Javascript vs. VBScript) but is not necessarily essential and, IIRC, has been deprecated.

window.onload() is not firing with IE 8 in first shot

I am trying to make my pages work correctly with IE 8, I found out from here: http://www.masykur.web.id/post/How-to-Make-Our-Website-to-be-Ready-for-IE8.aspx
that, my page has to be XHTML 1.0 compliant and atleast CSS 2.1 compliant, I made my page and CSS compliant with only few warnings, but still window.onload() is not firing. Does anybody encountered this problem?
here is the code snippet:
<!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" lang="en" xml:lang="en">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=8"/>
<title>Testing</title>
<link rel="stylesheet" href="test.css" type="text/css"></link>
<script type="text/javascript" src="login.js"></script>
<script type="text/javascript" src="common.js"></script>
<script type="text/javascript">
window.onload = function()
{
// Not coming here at all on first shot
}
</script>
</head>
<body>
.
.
.
However refreshing the page seems to make it work.
Am I missing something here?
UPDATE:
One of the IE addons created this problem, after disabling its working fine. Thanks for your time and answers :)
For IE try:
window.onload = new function() { alert('hello');};
This is a pretty old thread but I found a solution that might help others.
I was adding a function to window.onload via a dynamically injected script (really to mimic an external script load for reasons which are not important in this context). As stated in this post, on the first load within IE8, the window.onload would not fire, but all subsequent calls would.
I found out that if I put this in the HTML file as an internal script, it would work everytime:
var windowOnload = window.onload || function() {};
window.onload = function() { windowOnload(); };
All the above code does is "initializes" IE8's window.onload unobtrusively. I suspect that IE8 fails to trigger window.onload the first time if it is called from an external script as the onload event isn't attached yet to window (or in tech terms, its typeof is undefined). It seems that the first time that's what IE8 is doing: attaching onload to window without executing it properly.
The above code then becomes quite obvious: We are merely forcing IE8 to recognize the onload event. We don't care what gets executed, or what doesn't, so we simply make sure to pipe on through any existing window.onload code that is already defined (just as a precaution).
It is important to have this as an internal script to the HTML (at least from my testing).
Your HTML would thus look something like this (the relevant parts):
<script type="text/javascript">
var windowOnload=window.onload||function(){};window.onload=function(){windowOnload();};
</script>
<script type="text/javascript" src="script.js">
</script>
From my testing, after clearing cache, and reloading the page, I have gotten window.onload to successfully trigger each time.
I hope this helps.
You could have an error in your JavaScript's, if that happens, any JavaScript after that will not function correctly.
Try to remove the reference to login.js and common.js and try an alert within your problematic function.
I don't have IE8 to personally test, but what does this test do?
<!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" lang="en" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Test IE 8</title>
<script type="text/javascript">
/* <![CDATA[ */
window.onload = function(){alert('Good morning!');}
/* ]]> */
</script>
</head>
<body>
<h1>Hello</h1>
<body>
</html>
If this test works as expected, try the CDATA bit around your internal JavaScript block.
And then, if that does not work as expected, there is probably something in the external JavaScript above it that prevents your onload from firing. The previous poster mentioned this. At that point, try your error console or debugger to point the way.
onload fires after ALL your content has loaded (including external images etc). It's possible those resources are taking a long time to load on the first go (before they are cached). Another possibility is an error in your code that only affects IE as is stopping your scripts (but only the first time is odd).
If you are getting different results using Apache vs. another web server (IIS?) and comparing the end result using IE8, then the differrence must be in the content type header being sent. Get the wget utility for your platform and see the headers that are produced. If you are on Windows, then the Portable Apps version of the GUI wget is pretty nice.
The following code works for me. When I load the page in Firefox I see the alert instantly. When I first load the page in IE 8 it warns me about active content. If I allow the blocked content it asks me to confirm, which I do. Then the alert appears as expected. If this does not work for you, try IE 8 on a different computer or start eliminating code in your page to check for errors. You could do a binary search: comment out the first half of the page and see if the alert appears; if it still does not, then uncomment out the first half and comment out the second half. Repeat as needed until you've narrowed it down to the offending code. Incidentally you don't need XHTML for IE8 compliance. HTML works fine and actually has some advantages.
<!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" lang="en" xml:lang="en">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=8"/>
<title></title>
<style type="text/css">
</style>
<script type="text/javascript">
window.onload=function() { alert('hello');};
</script>
</head>
<body>
</body>
</html>
I know this is kinda old question, but I just faced the same thing.
window.onload=function() { alert('hello');};
is treated differently than
window.onload= new function() { alert('hello');};
The keyword here is new.
My JS was terminating whenever it reaches (onload=) part until I added the word'new' before 'function'. Even though it worked fine without 'new' in my localhost, but once I put it online, it doesn't work until I add 'new'.
Old question but I had the same issue but it turned out to be another problem. My problem was that I did <script type="application/javascript"> which <IE9 does not understand or try to run even. For it to work for older browsers you still have to use text/javascript even though this isn't technically the correct type...

Categories

Resources