I have a script that uses $(document).ready
, but it doesn't use anything else from jQuery. I'd like to lighten it up by removing the jQuery dependency.
How can I implement my own $(document).ready
functionality without using jQuery? I know that using window.onload
will not be the same, as window.onload
fires after all images, frames, etc. have been loaded.
How about this solution?
Here is the smallest code snippet to test DOM ready which works across all browsers (even IE 8):
See this answer.
I simply use:
And unlike
document.addEventListener("DOMContentLoaded" //etc
as in the very top answer, it works as far back as IE9 -- http://caniuse.com/#search=DOMContentLoaded only indicates as recently as IE11.For instance, go to https://netrenderer.com/index.php, choose Internet Explorer 9 from the dropdown, enter https://dexygen.github.io/blog/oct-2017/jekyll/jekyll-categories/liquid-templates/2017/10/22/how-jekyll-builds-site-categories.html and click "Render", and you will see something akin to the screenshot at the bottom of this post.
See the following Javascript code I am using in the header to manipulate the style of the Jekyll "hacker" theme to my liking -- in particular you can reference the
if (location.pathname !== rootPath)
block to see how I am inserting theHome
andBlog Home
links, which are being displayed by IE9 per the NetRenderer site.Interestingly I stumbled upon this
setTimeout
solution in 2009: Is checking for the readiness of the DOM overkill?, which probably could have been worded slightly better, as I meant by using various frameworks' more complicated approaches.If you don't have to support very old browsers, here is a way to do it even when your external script is loaded with async attribute:
Place your
<script>/*JavaScript code*/</script>
right before the closing</body>
tag.Admittedly, this might not suit everyone's purposes since it requires changing the HTML file rather than just doing something in the JavaScript file a la
document.ready
, but still...The setTimeout/setInterval solutions presented here will only work in specific circumstances.
The problem shows up especially in older Internet Explorer versions up to 8.
The variables affecting the success of these setTimeout/setInterval solutions are:
the original (native Javascript) code solving this specific issue is here:
this is the code from which the jQuery team have built their implementation.