Back to blue

Load on demand

This is a feature to load scripts on demand.

Make sure to include the JS into your page or project:

<script src="{{ static("js/ca_sg_load_on_demand.js") }}"></script>

Implementation

To load a JS file on demand, you need to add the attributes data-load-on-demand and data-src to the script tag. Example:

<script data-src="[SCRIPT_PATH]" data-load-on-demand="[SCRIPT_NAME]"></script>

On the page load event, the load on demand script will query and store all the elements that have the data-load-on-demand attribute and it will start listening the com.consumeraffairs.styleguide.loadOnDemand event.

When this event is dispatched, the load on demand feature expects receive the name of the scripts that should be loaded in the event detail required_scripts key. Example:

const detail = { required_scripts: ['ca_sg_modal', 'ca_sg_search'] }; const loadOnDemandEvt = new CustomEvent('com.consumeraffairs.styleguide.loadOnDemand', { detail }); document.dispatchEvent(loadOnDemandEvt);

It will then replace each script (listed in the "required_scripts" array) src attribute by their data-src attribute value.

Example

This example will load on demand the "ca_styleguide_search" script that has the "data-load-on-demand" attribute.

Click on the button below to dispatch the "com.consumeraffairs.styleguide.loadOnDemand" and see that script being loaded. You can either check the "ca_styleguide_search" script itself or the Network tab on the browser inspector to make sure it was loaded.