Google
 

« Making Cookies Work in IE         More Patent Insanity »

Changing Web Page Content on the Fly

Posted October 12, 2004 – 6:31 pm by Yakov Shafranovich in Programming

An interesting problem that comes up often is a need to change a part of a web page without reloading the entire page. This is especially true when dynamic content like a list needs to be generated from a database and included in the page. The solution to this is to do a dynamic Javascript include - programatically include a JavaScript file that can be generated dynamically, lets say by a servlet. The usual way to do that is via “document.write()” and include a “SCRIPT” tag in the web page. A more cleaner way is discussed in an article written by Moshe Moskowitz by DOM:

var scriptElement = document.createElement("script");
scriptElement.src = url;
scriptElement.type="text/javascript";
getObject('someSection').appendChild(scriptElement);

Now, what happens if your dynamic content generator also gives error pages in plain HTML? The code above will not work if an error occurs since the input provided will be HTML, not Javascript. So a workaround for this is to make the error pages do both JavaScript and HTML by adding the JavaScript code to the beginning of the HTML page and commenting it out with HTML comment tags. Then you can use JavaScript comment tags to comment out the HTML file itself. The result will execute JavaScript if included dynamically in a SCRIPT tag, and will show proper HTML (and even validate) if thrown in regular HTML processing. Here is a complete example with JavaScript content in red and HTML content in blue:

<!–
alert(’ERROR: Can’t find webpage [404]!’);
/*
–>
<HTML>
<BODY>
<H1>ERROR: Can’t find webpage [404]!</H1>
</BODY>
</HTML>
<!–
*/ // –>

The JavaScript code is enclosed in an HTML comment tag making it invisible by browsers. However, when executed as a JavaScript tag, it will execute until it hits a JavaScript comment tag “/*” which is ignored by browsers. The closing tag on the bottom and the followup “//” comment tag make sure that the JavaScript ignores the HTML content. BUT at the same time the two sets of HTML comment tags on the top and bottom make sure that the browser ignores all JavaScript code ignoring comment tags.

Tags: , ,

Permalink | Trackback URL | This post has

Sorry, comments for this entry are closed at this time.