For the following iframe, Safari never calls the onload function and doesn't display anything in the iframe. All other browsers I've tested do call onload and display a default error web page.
<html>
<body>
<iframe src="http://www.asdkjhjhkjhkjhjhjhfhkjhsdflkjahdsjfhasf.com"
onload="alert('iframe loaded');">
</iframe>
</body>
</html>
Why is this happening? If there is no solution to this problem, then I need to find a way to detect if an iframe fails to load.
I just the other day stumbled upon this post with a workaround for the missing load event
in Safari. The post is from 2011 but seems to be still valid.
The solution proposed there for Safari is to check for the readyState
event on the iframe
's document
like so:
<iframe id="ifra" src="http://www.asdkjhjhkjhkjhjhjhfhkjhsdflkjahdsjfhasf.com"
onload="alert('iframe loaded');">
</iframe>
<script>
var iframe = document.getElementById('ifra'),
doc = iframe.contentDocument || iframe.contentWindow;
if (doc.document) doc = doc.document;
var _timer = setInterval(function() {
if (doc.readyState == 'complete') {
clearInterval(_timer);
alert('iframe ready');
}
}, 1000);
</script>
As per Mozilla's documentation on contentDocument, you wouldn't need to include the workaround with the contentWindow
when running this script only in Safari, but I kept it in here in case you want to use it across browsers.