Centralize JavaScript: Request Data and Markup Only

Note

Separating out your JavaScript, HTML, and CSS layers can help alleviate many of the issues that Caja introduces in a fully embedded system.

As we have touched on once or twice already, the Caja client-side sanitizer can be a much stricter system than the server-side cajoler. This client-side part of Caja tends to strip out all JavaScript and any potentially malicious HTML and CSS from the data being pushed on the site or application.

This issue will surface when the developers are trying to make HTTP requests—such as a standard AJAX request—to another source to obtain new content for the web application. The client-side sanitizer springs into action when the request completes and the content is about to be inserted into the application via an innerHTML call, through creating new DOM nodes and appending them to the application, or by way of any other similar insertion utility.

Let’s say we have an application that has multiple pages. When a user clicks on a new page, an AJAX request fetches new markup for the page from the server and then replaces the current page when the request completes. Some developers might tend to encapsulate each page as a single unit, including the required JavaScript to run that particular page right in the markup that is returned to the application. This is where the trouble will arise, since the client-side sanitizer will strip all of that JavaScript from the return.

One of the best options for implementing this type of application structure is to centralize all JavaScript and load it when the application first loads, putting it under the less restrictive server-side cajoler parsing utility. When I say “centralize,” I am referring to the load time, not a single file—JavaScript files should be broken up into logical sections, preferably minified.

Questions often arise from this discussion about attaching events to markup if inline JavaScript markup such as onclick, onkeypress, or the like is removed. Once the new markup is inserted into the application, events can be attached to their logical points. Our last tip, “Don’t Embed Events in Markup,” outlines the steps you should take to insert events into existing markup.

Many developers may argue that these are general best practices anyway, which should be followed even when they’re not under the umbrella of Caja’s cajoler and sanitizer.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.189.228