When those commands are entered into the console, the symbol $
is not representative of jQuery. Instead, it functions as a helpful tool provided by the web browser that closely resembles document.querySelector
. More information on built-in helper functions for certain browsers can be found in the documentation.
The source code for Firefox's implementation of $
can be viewed here:
WebConsoleCommands._registerOriginal("$", function(owner, selector) {
try {
return owner.window.document.querySelector(selector);
} catch (err) {
throw new owner.window.DOMException(err.message, err.name);
}
});
Even if $
actually represented jQuery, the line:
$(document).ready(function(){
would not yet reference jQuery since the script has just been inserted and may not have finished downloading and parsing. Therefore, it would still point to the querySelector
alias. Similarly,
document.querySelector(document)
does not serve any meaningful purpose.
A recommended approach would be to attach a load
handler to the inserted script to execute a function once jQuery is fully loaded. For instance:
const jq = document.createElement('script');
jq.src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js";
document.head.appendChild(jq);
jq.addEventListener('load', () => {
console.log("hello world");
console.log($ === jQuery);
});
Upon successfully loading jQuery, window.$
will now refer to jQuery
rather than the querySelector
alias. The above snippet will output true
after a short delay.