non-jquery document ready - is window.onload the best/only way?
I want a function to run when the document
is ready, but there's no logical reason to leverage jquery as the little amount of work going on the page doesn't warrant me loading a file of that size.
Typically I would use window.onload = function(){};
-- as far as 开发者_开发知识库I can tell, this is the recommended approach.
Thoughts/recommendations? I would very much like to hear some developer opinions on this if there's a better way.
Note- If this question is better asked elsewhere (because it's somewhat subjective) - please let me know and I'll close it and ask there.The problem with window.onload
is that it will wait for all content (like images) to be loaded. Typically you only need for the DOM to be ready to be manipulated. You should know though that jQuery eliminates a lot of the cross browser inconsistencies in doing that, and as such doing it yourself will be a small pain in the ass. For that reason, you might want to look into this library which contains the bare bones of cross-browser DOM readiness.
If you want to have an universal supported method for a non-JQuery "domready" event, an option is to create a function which should be executed when the DOM is ready, and add a <script>
tag at the end of the document:
...
<script>
function runOnceReady(){
...
}
</script>
</head><body>
....
<script>runOnceDomReady()</script>
</body></html>
Write the equivalent of jQuery.ready event. jQuery is just javascript, so there is no reason you couldn't make a similar event. It is just there to reduce you're work at making your code browser compatible.
You could add an onload
to your body
tag on the page.
Do something like:
<body onload="myCrazyFunction()">
精彩评论