Sitecore and RegisterClientScriptInclude / RegisterClientScriptBlock / RegisterClientScriptResource

One of the common issues when using Sitecore HTML Caching is how to execute dynamic scripts based on code behind actions when the control front end is being cached.

The solution listed below defines the theory behind the approach rather than the concrete implementations.

Consider the following scenario:
You need to display the date to the user using javascript. To solve the issue, you decide to make use of either RegisterClientScriptBlock or RegisterStartupScript and register some javascript to write out alert(‘DateTime.Now’) [psuedo code].

This works fine during development since you are building your project a lot and the full use of caching isnt implemented. Down the line, you tune up / turn on caches and the date is only shown the first load after the caches are emptied 🙁

Do not fear, there is a solution to the issue and that is to make use of Sitecore Html Cache. Rather than calling asp.net RegisterClientScriptInclude(Block, Resource), setup your own methods (for the demo, these are exposed off SScriptManager):

In your master page, add another control (for the demo, known as SScriptManager).

When you register the script includes / blocks, store this information in the html cache remembering to build the cache key from current item, current language and script key.

During the Render/PreRender phase of the page lifecycle, the SScriptManager can then iterate through all keys in html cache and if the keys match the current page, relay on the script calls to the page.

Leave a Reply

Your email address will not be published.