How to check if an embedded SVG document is loaded in an html page? How to check if an embedded SVG document is loaded in an html page? jquery jquery

How to check if an embedded SVG document is loaded in an html page?


On your embedding element (e.g 'embed', 'object', 'iframe') in the main document add an onload attribute which calls your function, or add the event listener in script, e.g embeddingElm.addEventListener('load', callbackFunction, false). Another option might be to listen for DOMContentLoaded, depends on what you want it for.

You can also add a load listener on the main document. jQuery(document).ready doesn't mean that all resources are loaded, just that the document itself has a DOM that is ready for action. However note that if you listen for load on the entire document your callback function won't be called until all resources in that document are loaded, css, javascript etc.

If you use inline svg, then jQuery(document).ready will work just fine however.

On a further note you might want to consider using embeddingElm.contentDocument (if available) instead of embeddingElm.getSVGDocument().


You could use an onload event for the check.

Suppose some.svg is embedded in object tag :

<body>    <object id="svgholder" data="some.svg" type="image/svg+xml"></object></body>

Jquery

var svgholder = $('body').find("object#svgholder");svgholder.load("image/svg+xml", function() {    alert("some svg loaded");});

javascript

var svgholder = document.getElementById("svgholder");svgholder.onload = function() {    alert("some svg loaded");}


Assuming your SVG is in an <embed> tag:

<embed id="embedded-image" src="image.svg" type="image/svg+xml" />

The SVG image is essentially in a sub-document that will have a separate load event to that of the main document. However, you can listen for this event and handle it:

var embed = document.getElementById("embedded-image");embed.addEventListener('load', function(){    var svg = embed.getSVGDocument();    // Operate upon the SVG DOM here});

This is better than polling as any modification you make to the SVG will happen before it is first painted, reducing flicker and CPU effort spent painting.