The new Node-RED Dashboard 2 modules are great! But loading multiple external scripts in a particular order (e.g. the great HighChart visualization libraries) into a template node is a little bit of a pain.

I write a little script, that can be put into a template node, e.g. into a UI-scoped Widget, that can load multiple scripts in the exact order wanted. A global variable is set to check, if all scripts are loaded successfully. 


<template>
</template>

<script>
   
    window.customScriptsLoaded = false;
    
    // scripts to load in desired order
    let scripts = [
        'http://host.abc/first.js',
        'http://host.abc/second.js',
        'http://host.abc/third.js',
        'http://host.abc/fourth.js',
    ];

    function loadScripts(sources) {
       
        const loadScript = (src) => {
            return new Promise((resolve, reject) => {
                const script = document.createElement('script');
                script.src = src;
                script.async = false; // Ensure synchronous loading
                script.onload = resolve;
                script.onerror = reject;
                document.head.appendChild(script); // Append to the head
            });
        };

        const loadAllScripts = async () => {
            let count  =  0;
            for (const src of sources) {
                try {
                    await loadScript(src);
                    console.log(`Script loaded: ${src}`);
                    count ++;                    
                } catch (error) {
                    console.error(`Error loading script: ${src}`, error);
                }
            }
            if (count === sources.length)
                window.customScriptsLoaded = true;
        };
       
        loadAllScripts();
    }

    loadScripts(scripts);
   
</script>

<style>
</style>

So, later, in your template components, you can do this:

mounted() {
            let interval = setInterval(() => {
              if (window.customScriptsLoaded) {
                  // do something with important
                  clearInterval(interval);
              }
          }, 100);
}

Kommentare

Beliebte Posts aus diesem Blog

Using Amazon Echo Devices as Unifi Doorbell Chimes