Search code examples
demandware

How to add custom clientside javascript to demandware SiteGenesis homepage?


I am learning by working with SiteGenesis. I so far understands the basics of controllers and templates in demandware. I would like to understand how I can add client side javascript to a page in demandware. For example, the homepage of SiteGenesis has a controller in sitecore_controllers the render the homepage template. I would like to add a simple alert message to the users when the frot page load: alert('hello world'). I can hack around and insert this message somewhere, but I would like to do so by adding in my own cartridge and add a separate js file. What's the best-practice way of doing this?


Solution

  • You are correct that inline scripts are not the best practice here. In order to link a script file from your code you need to do the following:

    1. Add your script file to static/js folder of the cartridge.
    2. Using URLUtils class methods create a URL to this script file.
    3. Add script tag with src attribute pointing to the URL created in 2.

    Best practices now are to have these script tags right before the closing body tag. You may want to create a template for these script tags, and using a local isinclude tag, to include it from the decorator template, or from the footer template.

    Any questions - let me know.

    P.S. I have assumed that you know/understand:

    • the Script API classes URLUtils and URL;
    • how to print a value in a template;
    • local and remote includes (isinclude tag variants);
    • decorator and decorated templates (isdecorate, isreplace tags).