2

I use jQuery (which seems to use a glorified form of innerHTML document writing), to add a piece of HTML to the DOM:

    $newElem=$(HTML).appendTo($container);

The said HTML piece contains CSS links, which seem to load async. Images also load async.

I need some form of load event similar to window.load when async content is done fetching AND done parsing (i.e. CSS), because based on that I trigger a container resize/rearrange function, and sizing obviously depends on CSS, async images (and even async fonts but this last point is not an immediate concern for me). So how to get a proper load event for the DOM-added HTML?

Nickolay
  • 31,095
  • 13
  • 107
  • 185
Dinu
  • 1,374
  • 8
  • 21
  • You're correct about `.html()`. from the [jQuery docs](https://api.jquery.com/html/): "This method uses the browser's `innerHTML` property." – freginold Jul 31 '19 at 15:14
  • `$('img').on('load')` generally works. If you get that onto your appended images or delegate it, you should get that event firing. I am not sure if you can do the same for $('style').on('load'), but you might wanna give it a try – user3154108 Jul 31 '19 at 15:31
  • @user3154108 I was thinking of lumping together the `` and ``'s onload events into a whale of a promise; but there is at least one whale of a problem here: CSS's `content:url()`, which is the equivalent of writing an `` tag in CSS... and no onload for that then. I was hoping there would be a more semantically correct way of handling this. – Dinu Jul 31 '19 at 15:34
  • @Dinu aside from preloading the images from the CSS with Javascript before appending the CSS, I know of no way. – user3154108 Jul 31 '19 at 15:37

1 Answers1

1

I don't think there's a built-in "load" event that's fired when all the resources requested by the dynamically added elements are finished loading.

You can probably implement this though if you're sufficiently motivated.

There's waitForImages jQuery plugin, that goes through the given DOM subtree, looking for images (<img> tags as well as references to images in computed CSS styles). It creates an <img> element for each image referenced from CSS to track its load status (as discussed here).

It doesn't support:

  • content:url() images (should be easy to add)
  • Tracking resources referenced from dynamically loaded CSS. You can use a similar approach to find all the <link> elements in the given subtree, and use their load event (supported in all major browsers now) to wait until the CSS is loaded. After CSS finishes loading, run waitForImages to track the image loads.
Nickolay
  • 31,095
  • 13
  • 107
  • 185