4

I was wondering if there are any repercussions I can expect when changing from

$(document).ready(function() {...})

to

window.onload = function() {...}

The reason being I am making a widget and do not want to enforce a jQuery include in case the user already has it included in their app, nor do I want them to have to modify the widget code -- so I am dynamically determining if I should include it.

However, in order to dynamically include it, I do not have access to jQuery before the window.onload, which brings me to my scepticism.

My main worry is that this will disrupt the functionality of the user's app. So... will it?

Thanks in advance.

Garrett
  • 10,560
  • 17
  • 74
  • 120
  • possible duplicate of [window.onload vs document.ready](http://stackoverflow.com/questions/3698200/window-onload-vs-document-ready) – gion_13 Apr 20 '12 at 17:35

1 Answers1

2

Your function will actually fire in a different point in the page lifecycle. onload is called early in the lifecycle before all the page elements are necesarily loaded, whereas the ready event fires later. If you want to attach to the event without using jQuery, you can easily do that too:

document.addEventListener('DOMContentReady', function()
{
     // Stuff
});
Tejs
  • 38,896
  • 8
  • 64
  • 81
  • Something is up with that fiddle; even the `window.onload` event doesnt fire when I enter it in the script. – Tejs Apr 20 '12 at 17:20
  • Oh :P Well I have a plain page with `window.addEventListener('DOMContentReady', function() {alert('loaded');});` and still nothing. – Garrett Apr 20 '12 at 17:24
  • jsfiddle's injection of script frameworks was interfering with the event firing. – Tejs Apr 20 '12 at 17:32
  • ah, you use `document.onload` there. before you gave me `window.onload` :P thanks! – Garrett Apr 20 '12 at 17:59
  • Uh oh! IE7: `Object doesn't support property or method 'addEventListener'` – Garrett Apr 20 '12 at 18:04
  • You might need to use `attachEvent` – Tejs Apr 20 '12 at 18:06
  • You claim that "onload is called early in the lifecycle before all the page elements are necesarily loaded, whereas the ready event fires later", but this other answer with 225 upvotes claims the opposite (ready first, then onload later) http://stackoverflow.com/a/3698214/402807 – AlcubierreDrive Sep 09 '13 at 07:02
  • My answer is incorrect. The document ready event is fired first, then onload. – Tejs Sep 09 '13 at 21:40
  • For whatever reason, I was unable to get this listener to work either in google chrome 40. – Kzqai Mar 15 '15 at 14:33