fbpx

Tutorial

Javascript Eloquent way to check for dependencies

Uses Plugins

Elementor Free
Code Snippets

Description

A common issue when using JavaScript in Widgets and HTML fields is that dependencies have not yet loaded. This method ensures that all Dependencies have loaded before your script runs. It is asynchronous so it does not interfere with JavaScript execution. On Success or Fail, it dispatched an event so that any script relying on the same dependencies can listen for it and initialise only when the dependencies have loaded.

1

There are no steps for this tutorial

This tutorial is informational only, Please see the video for an explanation and the code below

Code (click to copy)

JS Code from Video (javascript)

<script>
    ;(() => {
        const checkInterval = 200;
        const checkTimeout = 1000;

        const globals = {
            IS_DEBUG : true,
            DEBUG_TYPE_LOG : 'log',
            DEBUG_TYPE_INFO : 'info',
            DEBUG_TYPE_WARN : 'warn',
            DEBUG_TYPE_ERROR : 'error'
        }

        const debug = (obj, type = globals.DEBUG_TYPE_LOG) => {
            if(globals.IS_DEBUG){ console[type](obj) }
        }

        /* Check for JS Dependencies on the JS Object */
        function checkDependenciesPromise(deps) {
            let elapsed = 0;
            const depsCount = deps.length;
            debug('First Dependency Check', globals.DEBUG_TYPE_INFO);
            return new Promise((resolve, reject) => {
                let timer = setInterval(() => {
                    let depsFound = 0;
                    deps.forEach( dep => {
                        if(window[dep]){ depsFound++}
                    })
                    if ( depsFound === depsCount ) {
                        debug('All dependencies found', globals.DEBUG_TYPE_INFO);
                        clearInterval(timer);
                        resolve('OK');
                    } else {
                        elapsed += checkInterval;
                        if (elapsed > checkTimeout) {
                            clearInterval(timer);
                            debug('Dependencies not found before timeout', globals.DEBUG_TYPE_ERROR);
                            reject('Missing dependencies');
                        }
                        debug('Next Check:' + elapsed, globals.DEBUG_TYPE_INFO);
                    }
                }, checkInterval);
            });
        }

        async function checkDependencies(deps, eventNameToFireOnSuccess, eventNameToFireOnFail) {
            await checkDependenciesPromise(deps)
            .then(()=>{
                const event = new CustomEvent(eventNameToFireOnSuccess);
                window.dispatchEvent(event);
            })
            .catch(e => {
                const event = new CustomEvent(
                    eventNameToFireOnFail,
                    {
                        detail: {
                            error: e
                        }
                    }
                );
                window.dispatchEvent(event);
            });
        }

        if(undefined === window.WPG_UTILS)( window.WPG_UTILS = {});
        window.WPG_UTILS.globals = globals;
        window.WPG_UTILS.debug = debug;
        window.WPG_UTILS.checkDependencies = checkDependencies;
    })();

    ;(()=>{
        const {checkDependencies, debug, globals} = window.WPG_UTILS;

        //Check Dependencies on Window
        checkDependencies(['ScrollTrigger','gsap'],'success/ScrollTrigger/gsap','failed/ScrollTrigger/gsap');

        window.addEventListener('success/ScrollTrigger/gsap', ()=>{
            debug('Start of code init', globals.DEBUG_TYPE_INFO);
        })
        window.addEventListener('failed/ScrollTrigger/gsap', (e)=>{
            debug(e.detail.error, globals.DEBUG_TYPE_ERROR);
        })


        debug('END OF SCRIPT', globals.DEBUG_TYPE_INFO)
    })();
</script>