Background:
The second “context” argument to invoke the jQuery selector (for example, jQuery(selector, context) ) can be provided to give the selector engine the starting point from which to descend.
This is often useful if you need to control content in an IFRAME (in the same domain). You simply pass iframe.contentWindow.document as the "context" argument.
If any JavaScript code is loaded into an IFRAME that uses jQuery and CALLED FROM EXTERNAL WINDOWS , then any reference to $ or jQuery in this code will actually be a jQuery instance from an external window.
The problem occurs when the JavaScript code in the IFRAME (for example, Bootstrap.js) does something like $(document) (or does some other selector without the "context" argument). When this code (defined inside an iframe) is called from an external window, document refers to the HTMLDocument element from the external window, which is usually not the desired result.
Question:
It would be very useful to create a lexically-copied copy / shell of jQuery that has a default context argument provided to those who create it.
Example:
// jQuery already exists out here var iframe = document.createElement('IFRAME'); iframe.addEventListener('DOMContentLoaded', function(){ // code in here can already refer to $ for 'outer' jQuery // code in here can refer to $local for 'inner' jQuery by virtue of... var $local = jQueryWithContext($, iframe.contentWindow.document); // code loaded with IFRAME will use $local by virtue of ... iframe.contentWindow.jQuery = iframe.contentWindow.$ = $local; }); iframe.src = '/path/to/iframe/content.html';
The question is, can I write something like jQueryWithContext above?
Why?
Sometimes you want to isolate third-party HTML components that (while you trust them in terms of security) are mistaken for the prospects of CSS / JavaScript pollution.
Bootstrap.js is a good example. It calls $(document) fair bit and makes other similar calls without context. If jQuery can be overridden in the way I describe, then these "not optimal" written libraries can be isolated quite easily.
It’s also very useful to use the same collection of $.data(el, ...) from both frames, and it’s quite complicated without any context management.