ejx
ejx

Reputation: 489

Out of memory error in IE(any) and Firefox when trying to include jQuery from parent document

I am dynamically loading iframes into a div. Those iframes need jQuery for their functionality. To avoid including jQuery into every single iframe I simply referenced jQuery in the iframe generator(the same code will be in the head of every iframe loaded) like so:

var jQuery = window.parent.$;  // The parent is the document that will house the iframes
var $ = jQuery;

This works just fine in Chrome and a substantial performance boost comes with loading jQuery only once. However both Firefox and IE start leaking memory like mad(both peak around 1gb of memory used) before throwing an out of memory error and dropping the script.

EDIT: jQuery 1.7 and jQueryUI 1.10.3(however jqUi is not used when loading the iframes)

Upvotes: 4

Views: 2697

Answers (1)

thwd
thwd

Reputation: 24818

Remember that jQuery keeps a context which represents the scope in which to seek for elements when selecting. The default context is the window.document of the page that included jQuery.

When referencing a parent frame's jQuery global, the context will still remain the parent's window.document, which implies that all selections you do will happen in the parent frame, which is almost never the desired effect.

This can, depending on the case (i.e. protocol, domain and port of the two frames), lead to weird behavior because of SOP restrictions.

Your best bet is to dynamically insert the <script> tag referencing the same jQuery resource as the parent in the child frame. The browser will most likely have the file in cache.

By the way, the answer linked by @undefined as a comment to your question is a terrible idea since it will only allow for string selectors to work correctly but doesn't consider all the other argument types the jQuery function can take (e.g. a function to be bound to document onload).

Upvotes: 1

Related Questions