Skip to content

Must Knows for Developers

Austin Gilbert edited this page Apr 11, 2023 · 7 revisions

Local Development with the plugin

Part of the reason the optimized JavaScript was placed in the filesystem rather than in the content tree was to avoid getting in SXA's way. Because of this and the Standalone/CM server's on-save event, developers are able to upload and make changes to the SXA Themes as they were before installing the plugin. This includes usage of the SXA CLI, Creative Exchange, or manually uploading the JavaScript files, and the "Optimized Scripts" command for the JavaScript files will automatically be run for you.

Additionally, the plugin only bundles the JavaScript without minification, so the usage of SXA's theme optimization system settings can still be used if developers wish to render the un-minified/un-optimized JavaScript locally. Switching back and forth from these settings may require the "Optimized Scripts" command to be run.

Development Preparation

If you are using SXA 100% outside of the box with no custom JavaScript, then you most likely won't need to do any development preparation. However, since the plugin loads the JavaScript at the top of the HTML DOM and asynchronously, you must ensure that any JavaScript waits until a given page is ready before executing by wrapping your code with an event listener. You can use SXA's XA JavaScript framework, but if you are looking to optimize your JavaScript further and simply execute code as soon as it can be executed, you can use the following options depending on the situation.

SXA's XA Framework

XA.component.yourComponent = (function ($) {
    var api = {};
    api.init = function () {
      // your code goes here
    };

    return api;

}(jQuery));

XA.register("yourComponent", XA.component.yourComponent);

jQuery

$(window).load(function() {
  // executes when complete page is fully loaded, including all frames, objects and images
});

$(document).ready(function() {
  // executes when HTML-Document is loaded and DOM is ready
});

$(function(){
 // shorthand for $(document).ready()...
});

Native JavaScript

Note: This will most likely be the most performant option

window.addEventListener("loaded", (event) => {
  // executes when complete page is fully loaded, including all frames, objects and images
});

window.addEventListener("DOMContentLoaded", (event) => {
  // executes when HTML-Document is loaded and DOM is ready
});

Along with ensuring that the JavaScript waits until it's supposed to be run, it will be much more important that your JavaScript is free of runtime errors and/or bugs. Before installing the plugin, JavaScript files containing runtime errors could easily have gone unnoticed depending on how isolated it was or the order of the file in the content tree. Now that all of the JavaScript files for the SXA themes are bundled in one file, the runtime errors will most likely cause the JavaScript to break and won't finish completely loading the file.