Roots Discourse

How to use the const ready in utils.js?

In Sage 10 (not sure if it was already there in previous versions) there is a utils.js with the code:

/**
 * Execute a function when the DOM is fully loaded.
 *
 * @param {function} fn
 */
export const ready = fn => document.readyState !== 'loading'
  ? window.setTimeout(fn, 0)
  : document.addEventListener('DOMContentLoaded', fn);

How would I be able to use it? I tried creating a function in utils.js and app.js named “DOMContentLoaded” yet I doesn’t seem to get triggered when the page loads.

Anyone has tip/hint on what I’m missing here?

Thanks

This code is using an arrow function (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) and a ternary operator (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator). If you read up on those languages features you should see what you’re missing.

1 Like

Can’t seem to get it working, the whole file seems to be not included anywhere. I got it solved differently. Thx anyways.

You should be able to use it like this from the routes:

/**
 * Home
 */
import { ready } from '../utils';

function yourFunction() {
  //--
}

export default () => {
  ready(yourFunction);
};
2 Likes