What is the non-jQuery equivalent of '$(document).ready()'?
To mimic $(document).ready()
in jQuery using vanilla JavaScript, use the DOMContentLoaded event to ensure code runs after the DOM is fully parsed yet prior to loading images and external resources.
Handling older browsers
For vintage browsers (nostalgia alert), especially IE8 and older, you may have to be more creative. Use the readyState
property and check when it's 'interactive'
, signifying the DOM is fully parsed.
Be sure to delve into MDN documentation to master the nuances of different readyState
values.
Versatile utility duo
Let's amp up your arsenal with utility functions that add flexibility and control, handling both DOM readiness and window loading (including all your images, scripts, plugins). Consider them your trusty cavalry.
Promises – The next level
To level up, let's make things smoother with Promises, thus making your logic more reliable and easy to manage.
Ditch jQuery – stay lean
Opt for lightweight and efficient alternatives at 'http://youmightnotneedjquery.com/#ready' to minimize dependence on jQuery. Stay lean, stay fast!
TypeScript assures type safety
For those using TypeScript, consider integrating it to add type safety to your utility helper functions to prevent accidentally passing non-executable arguments:
Don't forget to sweep up after the party by removing event listeners once they've done their job { once: true }
, to avoid lingering memory guests.
Mind the loading time
Remember, unlike DOMContentLoaded
, window.onload
chivalrously waits for every resource (including your images and iframes) to load. With separate listeners, you can manage sub-resource loading with finesse.
Practice with examples
Here are some examples, seasoned with some humor, for you to try your hands on. Remember, practice takes you from noobville to mastering .readyState
-fu faster than you can say DOMContentLoaded
.
Check out libraries such as domReady.js for hassle-free, ready-to-rock solutions.
Was this article helpful?