The question is so like a zillion others here and on the web - How to check if DOM has loaded in Javascript? But here's the catch:
- Without using a framework like jQuery etc;
- Without knowing if your script has been loaded via a statically placed
<script>
tag or via some other Javascript much later after the DOM has already loaded.
Can this be done more or less reliably and with cross-browser compatibility?
Added: Let me clarify: I'm writing a standalone .JS file which can be included in arbitrary webpages. I want to execute code AFTER the DOM has been loaded. But I don't know HOW my script will be included. It could be by placing a <script>
tag (in which case the traditional onload
or DOM-readiness solutions will work); or it could be loaded via AJAX or some other means, much later after the DOM is already loaded (so the previously mentioned solutions will never fire).
The
document.readyState
property can be used to check if the document is ready. From MDN:Code example: