Script type text javascript cdata if

Writing JavaScript for XHTML

In practise, very few XHTML documents are served over the Web with the correct MIME media type, application/xhtml+xml . Whilst authored to the stricter rules of XML, they are sent with the media type for HTML ( text/html ). The receiving browser considers the content to be HTML, and does not utilise its XML parser.

There are a number of reasons for this. Partially it is because, prior to version 9, Internet Explorer was incapable of handling XHTML sent with the official XHTML media type at all. (Rather than displaying content, it would present the user with a file download dialog.) But it is also founded in the experience that JavaScript, authored carefully for HTML, can break when placed with an XML environment.

This article shows some of the reasons alongside with strategies to remedy the problems. It will encourage web authors to use more XML features and make their JavaScript interoperable with real XHTML applications.

(Note that XHTML documents which behave correctly in both application/xhtml+xml and text/html environments are sometimes known as ‘polyglot’ documents.)

To test the following examples locally, use Firefox’s extension switch. Just write an ordinary (X)HTML file and save it once as test.html and once as test.xhtml.

Problem: Nothing Works

After switching the MIME type suddenly no inline script works anymore. Even the plain old alert() method is gone. The code looks something like this:

Solution: The CDATA Trick

This problem usually arises, when inline scripts are included in comments. This was common practice in HTML, to hide the scripts from browsers not capable of JS. In the age of XML comments are what they were intended: comments. Before processing the file, all comments will be stripped from the document, so enclosing your script in them is like throwing your lunch in a Piranha pool. Moreover, there’s really no point to commenting out your scripts — no browser written in the last ten years will display your code on the page.

The easy solution is to do away with the commenting entirely:

This will work so long as your code doesn’t contain characters which are «special» in XML, which usually means < and & . If your code contains either of these, you can work around this with CDATA sections:

Note that the CDATA section is only necessary because of the < in the code; otherwise you could have ignored it.

A third solution is to use only external scripts, neatly sidestepping the special-character problem.

Alternatively, the CDATA section can be couched within comments so as to be able to work in either application/xhtml+xml or text/html:

Читайте также:  Условия в питоне примеры

And if you really need compatibility with very old browsers that do not recognize the script or style tags resulting in their contents displayed on the page, you can use this:

See this document for more on the issues related to application/xhtml+xml and text/html (at least as far as XHTML 1.* and HTML 4; HTML5 addresses many of these problems).

Problem: Names in XHTML and HTML are represented in different cases

Scripts that used getElementsByTagName() with an upper case HTML name no longer work, and attributes like nodeName or tagName return upper case in HTML and lower case in XHTML.

Solution: Use or convert to lower case

For methods like getElementsByTagName(), passing the name in lower case will work in both HTML and XHTML. For name comparisons, first convert to lower case before doing the comparison (e.g., «el.nodeName.toLowerCase() === ‘html'»). This will ensure that documents in HTML will compare correctly and will do no harm in XHTML where the names are already lower case.

We found out already, that the document object in XML files is different from the ones in HTML files. Now we take a look at one widly used property that is missing in XML files. In XML documents there is no document.cookie. That is, you can write something like

in XML as well, but nothing is saved in cookie storage.

Solution: Use the Storage Object

With Firefox 2 there was a new feature enabled, the HTML 5 Storage object. Although this feature is not free of critics, you can use it to bypass the non-existing cookie, if your document is of type XML. Again, you will have to write your own wrapper to respect any given combination of MIME type and browser.

Problem: I Can’t Use document.write()

This problem has the same cause as the one above. This method does not exist in XMLDocuments anymore. There are reasons why this decision was made, one being that a string of invalid markup will instantly break the whole document.

Solution: Use DOM Methods

Many people avoided DOM methods because of the typing to create one simple element, when document.write() worked. Now you can’t do this as easily as before. Use DOM methods to create all of your elements, attributes and other nodes. This is XML proof, as long as you keep the namespace problem in focus (e.g., there is a document.createElementNS method).

Of course, you can still use strings like in document.write(), but it takes a little more effort. For example:

var string = '

Hello World!

'; var parser = new DOMParser(); var documentFragment = parser.parseFromString(string, "text/xml"); body.appendChild(documentFragment); // assuming 'body' is the body element

But be aware that if your string is not well-formed XML (e.g., you have an & where it should not be), then this method will crash, leaving you with a parser error.

Problem: I want to remain forward compatible!

Given the direction away from formatting attributes and the possibility of XHTML becoming eventually more prominent (or at least the document author having the possibility of later wanting to make documents available in XHTML for browsers that support it), one may wish to avoid features which are not likely to stay compatible into the future.

Solution: Avoid HTML-specific DOM

The HTML DOM , even though it is compatible with XHTML 1.0, is not guaranteed to work with future versions of XHTML (perhaps especially the formatting properties which have been deprecated as element attributes). The regular XML DOM provides sufficient methods via the Element interface for getting/setting/removing attributes.

Читайте также:  Chrome extension on typescript

Problem: My Favourite JS Library still Breaks

If you use JavaScript libraries like the famous prototype.js or Yahoo’s one, there is bad news for you: As long as the developers don’t apply the fixes mentioned above, you won’t be able to use them in your XML-XHTML applications.

Two possible ways still are there, but neither is very promissing: Take the library, recode it and publish it or e-mail the developers, e-mail your friends to e-mail the developers and e-mail your customers to e-mail the developers. If they get the hint and are not too annoyed, perhaps they start to implement XML features in their libraries.

I Read about E4X. Now, This Is Perfect, Isn’t It?

As a matter of fact, it isn’t. E4X is a new method of using and manipulating XML in JavaScript. But, standardized by ECMA, they neglected to implement an interface to let E4X objects interact with DOM objects our document consists of. So, with every advantage E4X has, without a DOM interface you can’t use it productively to manipulate your document. However, it can be used for data, and be converted into a string which can then be converted into a DOM object. DOM objects can similarly be converted into strings which can then be converted into E4X.

Finally: Content Negotiation

Now, how do we decide, when to serve XHTML as XML? We can do this on server side by evaluating the HTTP request header. Every browser sends with its request a list of MIME types it understands, as part of the HTTP content negotiation mechanism. So if the browser tells our server, that it can handle XHTML as XML, that is, the Accept: field in the HTTP head contains application/xhtml+xml somewhere, we are safe to send the content as XML.

In PHP, for example, you would write something like this:

if( strpos( $_SERVER['HTTP_ACCEPT'], "application/xhtml+xml" ) ) < header( "Content-type: application/xhtml+xml" ); echo ''."\n"; > else < header( "Content-type: text/html" ); >

This distinction also sends the XML declaration, which is strongly recommended, when the document is an XML file. If the content is sent as HTML, an XML declaration would break IE’s Doctype switch, so we don’t want it there.

For completeness here is the Accept field, that Firefox 2.0.0.9 sends with its requests:

Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5

Further Reading

You will find several useful articles in the developer wiki:

DOM 2 methods you will need are:

See also

Источник

How to put CDATA into script tag in XSLT

You have an XSL template for the website you are working on and you would like to embed some JavaScript in the markup. You care so you would like to keep the XHTML output valid. Easy enough — all it takes is wrapping the actual JavaScript code with CDATA. To make it safe you would also add JS comments around CDATA and move on. But is it really that easy with XSL? Let’s have a look.

Short story: JavaScript template

Here is the working solution which allows for safe embedding JavaScript on XHTML pages created with XSL templates. This is the fruit of rather lengthy trial and error session.

      <script type="text/javascript"> /* <![CDATA[ */  /* ]]> */ </script>       2) <> ]]>      

The above example will output:

Long story: can this be simpler?

Well, let’s have a look at a few different ways this problem can be approached and the results. For brevity I am showing only the script element.

Add CDATA directly in the script tag

What happened?

cdata-section-elements

xls:output has an option which allows to wrap content of certain tags with CDATA. However even if you set it up to wrap up content of script tags with CDATA (the rest of the code like in example 1) you will not get what you need. Let’s have a look.

 cdata-section-elements="script" /> 

What happened?

So. the script tag got its CDATA, but of course not safely escaped. And the CDATA that we have put into the XSL template is gone anyway. Similarly to what we have concluded above — as a XML construct it is interpreted in XSL as well. No good.

CDATA as text

How about creating CDATA explicitly as a text? Maybe with disabled output escaping that would work? Let’s see.
Example 3

What happened?

That’s definitely some progress, CDATA is in place, neatly commented out. Now the problem is < in the JavaScript code. We would prefer that to be < again.

JavaScript code as xsl:text

Why not to put the whole JavaScript code into another xsl:text tag with disable escaping?
Example 4

What happened?

Is it a dead end or maybe xsl:text element is not the best choice after all?

JavaScript code as xsl:value-of

We can see we are on to somthing. It has to be something with disable-output-escaping attribute. Another such element is xsl:value-of . Assuming that the JavaScript code exists only in the template and not in the processed XML structure, xsl:value-of needs an xsl:variable to read value from.
Example 5

What happened?

It worked! It is not very flexible solution, though. Defining variable for every JavaScript in the template seems to be acceptable only if necessary. Luckily xsl:value-of can also read value of a parameter passed to an xsl:template . That’s how I got to the template you can find at the top of the page.

Thank you for reading. I hope you found it useful.

Jacek Ciolek

Jacek Ciolek

How IE6 caused The Dark Decade of the Web

If each developer in the world gave me a penny for every time they were swearing at IE6 then I could possibly be the richest man on the planet. The money spent in

Zend PHP 5 Certification Exam — review

This time I’m going to write about the taking the Zend PHP5 exam, not about PHP. I have taken the exam today and singing loudly in my car on the way back home

Источник

Script type text javascript cdata if

Элемент CDATA содержит в себе текстовые данные, которые не должны быть проанализированы XML-парсером.

по-умолчанию, парсер воспринимает их как PCDATA .

Некоторые текстовые данные, например JavaScript, могут содержать множество символов » < " или " & ". Чтобы избежать ошибок, такие блоки должны быть определены как CDATA.

Всё внутри секции CDATA игнорируется XML-парсером.


Для браузеров, не понимающих признаков CDATA, внутри блоков скриптов и стилей CDATA рекомендуется «скрывать» с помощью комментариев.

Пример: CDATA внутри блоков сценариев javascript

Пример: CDATA внутри блоков стилей CSS

5 Комментариев :

О спасибо.
а CDATA влияет на js скрипт или нет?

Нет, не влияет. Но блоки CDATA рекомендуется «отбивать» комментариями.

Добавил примеры для javascript и CSS.

а вот как обратно.
столкнулся с проблемой того что в БД не валидный html, который нужно сохранить.
«Засунул» в CDATA, а обратно.

Анонимный, HTML «забивается» обычными комментариями. ЦДАТА тут не нужна. Либо программными средствами. Но вообще рекомендую перепроверить верстку в хорошем редакторе.

P.S. Ответ запоздал, но вдруг кому поможет 😀

Источник

Оцените статью