SyntaxError: '[object HTMLDocument]' 不是 Firefox 中的有效选择器

it_*_*ure 6 javascript firefox google-chrome

加载我的本地 js 库并运行警报命令。

var jq = document.createElement('script');
jq.src = "http://127.0.0.1/js/jquery-3.3.1.min.js";
document.getElementsByTagName('head')[0].appendChild(jq);
$(document).ready(function(){
alert("hello world");
});
Run Code Online (Sandbox Code Playgroud)

1.在chrome的inspect--console中
弹出一个窗口hellow world,没有问题。

2.在firefox的控制台中。
它遇到如下错误:

SyntaxError: '[object HTMLDocument]' is not a valid selector
Run Code Online (Sandbox Code Playgroud)

为什么代码片段无法在 Firefox 的控制台中运行?

Cer*_*nce 7

当这些命令输入到控制台时,$不是 jQuery - 相反,它是浏览器提供的一个与document.querySelector. 请参阅有关某些浏览器上可用的内置帮助程序函数的文档。

$ 您可以在此处查看 Firefox 的源代码:

WebConsoleCommands._registerOriginal("$", function(owner, selector) {
  try {
    return owner.window.document.querySelector(selector);
  } catch (err) {
    // Throw an error like `err` but that belongs to `owner.window`.
    throw new owner.window.DOMException(err.message, err.name);
  }
});
Run Code Online (Sandbox Code Playgroud)

即使$ 是jQuery,这条线

$(document).ready(function(){
Run Code Online (Sandbox Code Playgroud)

还不会引用 jQuery,因为您只是插入了脚本 - 它还不一定被下载和解析。所以,它仍然会引用querySelector别名,并且

document.querySelector(document)
Run Code Online (Sandbox Code Playgroud)

没有任何意义。

最好的解决方案是将load处理程序附加到插入的脚本,以便您可以在加载 jQuery 后运行函数。例如:

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);
});
Run Code Online (Sandbox Code Playgroud)

一旦 jQuery 加载,它将确保window.$ now指向jQuery而不是querySelector别名;true稍后将记录上面的代码片段。