Append script when dash components are loaded

An alternate approach to solving this kind of problem:

Use the built-in setInterval (a way to repeatedly call a JavaScript function every X seconds) to attempt to retrieve the dash component class/id you are after, and then turn off the calls with a function called clearInterval:

function myFunction() {
    let someComponentClass = document.getElementsByClassName("...");
    if(someComponentClass.length > 0) {
        clearInterval(refreshID);
    }
}

// call this function every 250 ms
let refreshID = setInterval(myFunction, 250);

Thanks for the snippet. But this gives a new type of error

Uncaught TypeError: Cannot read property 'length' of null

I understand why the error occurs, but how to address it? If you have any inputs, please share! Thank you.

Hmm, I imagine that all you have to do is add a check in the if line that determines whether the object is defined or not.

That would look something like this:

function myFunction() {
    let someComponentClass = document.getElementsByClassName("...");
    if(someComponentClass && someComponentClass.length > 0) {
        clearInterval(refreshID);
    }
}

// call this function every 250 ms
let refreshID = setInterval(myFunction, 250);

I referenced this stackoverflow post btw

Let me know if this helps.

3 Likes

Hi, Thanks but still gives the same error.

thanks! this solved the problem for me :slight_smile:

1 Like

Worked for me too ! Much thanks for the help @akulidjian :slight_smile:

1 Like

You’re most welcome!

I’ve tried using the library to import a javascript file from a server running on localhost and it doesn’t work.

what to do now ? i dont see any solution.

is there any official solution to this problem?

@pengz This is a very old thread. Might be better to start a new topic and describe what solution you are looking for.

Thank you for answering, I still have this problem and there doesn’t seem to have any official solution yet.

Can you provide a minimal example of what you have tried so far?

The problem is exactly like what this post suggests, and I’ve tried the solution from @akulidjian and it worked, but it’s not the optimal solution. And I don’t want to download third-party libraries as other posts suggest which is not maintained. I am just wondering if there’s any official way to append the scripts after the components are loaded, instead of scripts being loaded in the beginning. And client_side callback does not work in this case as it is an animation js that needs to run infinitely.

You can use this component,

https://www.dash-extensions.com/components/defer_script

2 Likes

Or, if you don’t want to use dash-extensions, you can add a clientside callback that adds a script tag to the body of the document.

var newScript = document.createElement(“script”)
newScript = your src
document.body.append(newScript)

3 Likes