How can I detect if a Flash file is already loaded before calling the embed function?
I’m working with a Flash chart component and need to prevent multiple loading attempts. Here’s my current setup:
<head>
<script>
function loadChart() {
swfobject.embedSWF(
"chart-component.swf",
"flashContainer",
"500",
"300",
"10.0.0",
"install.swf",
{"data-source": "{% url chart-data %}"}
);
}
</script>
</head>
<div id="flashContainer"></div>
<script>
loadChart();
</script>
The issue is that I want to execute the loadChart() function only when the SWF file hasn’t been embedded already. I need to check the loading state to avoid duplicate embeddings. What’s the best approach to verify if the Flash object is already present in the DOM before attempting to load it again?
yea, that’s a good point! just make sure u check if that container ain’t got no kids in it before embedding, like if(document.getElementById('flashContainer').children.length == 0) { loadChart(); } that way u won’t load it twice.
Check the swfobject registry directly instead of DOM inspection. I ran into this exact issue with multiple chart instances. Use swfobject.getObjectById() to verify your Flash object exists before embedding - it checks swfobject’s internal registry, not just DOM elements. javascript function loadChart() { if (!swfobject.getObjectById('flashContainer')) { swfobject.embedSWF( "chart-component.swf", "flashContainer", "500", "300", "10.0.0", "install.swf", {"data-source": "{% url chart-data %}"} ); } } This handles cases where the Flash object’s in different loading states that DOM checking misses. Works consistently across browsers and Flash versions.
I’ve worked with Flash components for years. Boolean flags beat DOM checking every time for tracking loading state. Set a global variable when embedding starts, clear it when done. Use var chartLoaded = false; at the top, then wrap embedSWF like this: if (!chartLoaded) { chartLoaded = true; swfobject.embedSWF(...); }. Add a callback parameter to embedSWF for loading failures - reset your flag if the SWF fails. This saved me from nasty race conditions when users spam the refresh button.