Running dynamically loaded jQuery after dynamically loaded content has finished loading

753 Views Asked by At

I'm dynamically sending an html snippet to the browsers. This snippet contains an SVG and a piece of Javascript:

<div class="traffic-map-wrap">
    <embed id="traffic-map" type="image/svg+xml" class="traffic-map" src="{traffic-map-svg}" />
</div>

<script>
  $(function() {
    svgPanZoom('#traffic-map', {
      zoomEnabled: true,
      controlIconsEnabled: false,
      minZoom: 0.1,
      maxZoom: 10000
    });
  });
</script>

The function in the snippet runs fine, but the svgPanZoom fails because it is being run before the SVG is fully loaded (TypeError: e.getSVGDocument(...) is null). On the other hand if I introduce an alert() and give it a couple of seconds before clicking, it all works fine:

<script>
  $(function() {
    alert();
    svgPanZoom('#traffic-map', {
      zoomEnabled: true,
      controlIconsEnabled: false,
      minZoom: 0.1,
      maxZoom: 10000
    });
  });
</script>

Obviously this is not a glorious solution so how can I run a dynamically loaded script after everything has been loaded? Some equivalent of $(window).load(function(){...});?

1

There are 1 best solutions below

3
On BEST ANSWER

Try checking recursively if SVG was loaded...

$(function() {
    svgPanZoom_launcher();
});

function svgPanZoom_launcher() {
    var svg = document.getElementById("traffic-map").getSVGDocument();
    if (svg == null) {
        setTimeout("svgPanZoom_launcher()", 400);
    } else {
        svgPanZoom('#traffic-map', {
            zoomEnabled: true,
            controlIconsEnabled: false,
            minZoom: 0.1,
            maxZoom: 10000
        });
    }
}