Bug Tracker

Opened 13 years ago

Closed 12 years ago

#904 closed bug (fixed)

DOM ready handlers will never be executed if jQuery is dynamically loaded

Reported by: Arrix Owned by: john
Priority: minor Milestone: 1.2.2
Component: event Version: 1.1.3
Keywords: domReady ready Cc:
Blocked by: Blocking:

Description (last modified by john)

If jquery.js is dynamically loaded into a page, document ready will never be triggered.

<script type="text/javascript">
window.onload = function() {
	var s = document.createElement('script');
	s.type = 'text/javascript';
	s.src = 'jquery.js';
	document.getElementsByTagName('head')[0].appendChild(s);
	
	document.onclick = function() {
		alert($.isReady);
	}
};
</script>

IE, Firefox and Opera will alert "false" after you click on the page. Haven't tested in Safari yet.

Change History (7)

comment:1 Changed 13 years ago by joern

How can a script detect how it was loaded?

comment:2 Changed 13 years ago by john

Milestone: 1.1.3
need: Test Case

comment:3 Changed 13 years ago by john

Description: modified (diff)
Milestone: 1.1.31.1.4
Owner: set to john
Version: 1.11.1.3

I think I've got an idea on how this might work. When jQuery is loaded, it traverses down to see what the last element in the document is, if it's a script element, then we're being loaded naturally. If it's not, then we're being loaded dynamically (and thus the document 'is ready').

comment:4 Changed 13 years ago by john

Humm... that won't work, though, if the last element on the page is, in fact, a script element. For example:

  document.body.appendChild(script);

Lame.

comment:5 Changed 13 years ago by arrix

When jQuery loads, we can first check whether the document is ready. If so, mark jQuery.isReady true.

John has discovered great new techniques to check whether the document is ready :-)

"If you attempt to insert into the document.body before the document is fully loaded, an exception is thrown. I take advantage of that to determine when the document is fully loaded."

WOW, we can now hopefully fix this!

comment:6 Changed 13 years ago by john

@arrix: Unfortunately, that only works in IE - and only sometimes. There's ways to determine if the DOM is ready in IE, Safari, and Opera - all using document.readyState. Unfortunately, Firefox doesn't provide this property, so an alternative hack will have to be found.

comment:7 Changed 12 years ago by brandon

Milestone: 1.1.41.2.2
Resolution: fixed
Status: newclosed

As of Rev [4162] you can manually trigger the ready code. So once jQuery and your scripts are loaded you can run this line to trigger the ready event.

$(document).trigger("ready");

I believe this is about as fixed as this will get for now.

Note: See TracTickets for help on using tickets.