use*_*567 19 javascript jquery html5 web-worker
我无法在HTML5 Web工作者中访问jQuery .有没有办法可以做到这一点?
Tom*_*ica 22
JQuery最初访问许多document属性以检查浏览器功能.document在Worker中未定义,此时您实际上无法Document在Web worker中创建实例.JQuery没有为此做好准备 - 正如你在评论中看到的那样,没有人似乎明白你在没有DOM的情况下对JQuery做什么.
因为,正如我所说,JQuery需要document初始化,我创建了一个假的伪文档对象.在JQuery测试期间,此对象充当真实文档:
var document = self.document = {parentNode: null, nodeType: 9, toString: function() {return "FakeDocument"}};
var window = self.window = self;
var fakeElement = Object.create(document);
fakeElement.nodeType = 1;
fakeElement.toString=function() {return "FakeElement"};
fakeElement.parentNode = fakeElement.firstChild = fakeElement.lastChild = fakeElement;
fakeElement.ownerDocument = document;
document.head = document.body = fakeElement;
document.ownerDocument = document.documentElement = document;
document.getElementById = document.createElement = function() {return fakeElement;};
document.createDocumentFragment = function() {return this;};
document.getElementsByTagName = document.getElementsByClassName = function() {return [fakeElement];};
document.getAttribute = document.setAttribute = document.removeChild =
document.addEventListener = document.removeEventListener =
function() {return null;};
document.cloneNode = document.appendChild = function() {return this;};
document.appendChild = function(child) {return child;};
Run Code Online (Sandbox Code Playgroud)
请注意,这个假文档只是为了允许加载jQuery,它不允许任何真正的DOM操作.
importScripts("workerFakeDOM.js");
importScripts('jquery-2.1.4.min.js');
console.log("JQuery version:", $.fn.jquery);
Run Code Online (Sandbox Code Playgroud)
允许您使用我的脚本尝试各种版本的JQuery.
检查您是否正在使用http://,我的域名无法使用https://.
TomášZato的答案是正确的,但不再适用于较新的jQuery版本.我为jQuery 3.1.1添加了一些:
var document = self.document = { parentNode: null, nodeType: 9, toString: function () { return "FakeDocument" } };
var window = self.window = self;
var fakeElement = Object.create(document);
fakeElement.nodeType = 1;
fakeElement.toString = function () { return "FakeElement" };
fakeElement.parentNode = fakeElement.firstChild = fakeElement.lastChild = fakeElement;
fakeElement.ownerDocument = document;
document.head = document.body = fakeElement;
document.ownerDocument = document.documentElement = document;
document.getElementById = document.createElement = function () { return fakeElement; };
document.createDocumentFragment = function () { return this; };
document.getElementsByTagName = document.getElementsByClassName = function () { return [fakeElement]; };
document.getAttribute = document.setAttribute = document.removeChild =
document.addEventListener = document.removeEventListener =
function () { return null; };
document.cloneNode = document.appendChild = function () { return this; };
document.appendChild = function (child) { return child; };
document.childNodes = [];
document.implementation = {
createHTMLDocument: function () { return document; }
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18107 次 |
| 最近记录: |