Berbare
Berbare

Reputation: 144

How to detect an external javascript has finished rendering its dynamically-loaded HTML?

In my website (using jQuery 1.11) I must make use of an external script that renders its own HTML inside of a div I specify for it. Since it takes a considerable time, it is deferred.

For now, in order to know when its content are loaded, I created a function that after a small timeout, tries to detect the content through a $(selector).length call, and depending on this result, it either a) sets a longer a timeout to call itself again, or b) finds the content and sets up the .on()-like events I need to set up on the loaded content.

Is there a simpler way? I feel like this is over complicated. Notice:

Upvotes: 1

Views: 484

Answers (2)

Ser
Ser

Reputation: 2890

If you can edit your external script:
Before loading your external script, create some event handler, then when your algorithm is done, just send the expected event. All your JS code share the same window.document, so you can use it :

    window.document.addEventListener('plugin', (event) => {
      // Your script have sent the event
    })

Then send the event on the plugin side

  const event = new CustomEvent('plugin', {
    detail: {
      // Here I send the current plugin script uri, can be used if the event handler is used by several script (not your usecase) 
      sourcePath: document.currentScript.src,
    },
  })
  document.dispatchEvent(event)

We use scriptjs to load dynamically external JS file and it works well.

Upvotes: 1

Quentin
Quentin

Reputation: 944083

Is there a simpler way?

Not to achieve the goal you specified in the question title without doing the things you have ruled out.

You could, however, use delegated events.

Bind the event handler to an element you know exists before the script runs, and wait for the events to bubble up to it.

$("#div-I-specify-for-it").on("click", ".element-inside-div", (event) => alert("example"));

Upvotes: 1

Related Questions