如何在HTML 5 web worker中访问jQuery [英] How to access jQuery in HTML 5 web worker
问题描述
我无法访问HTML5 网络工作者内部的jQuery。有没有一种方法可以做到这一点?
I am unable to to access jQuery inside an HTML5 web worker. Is there a way I can do that?
推荐答案
tl; dr:include 这个脚本在jQuery之前
JQuery初始化访问大量的文档 code>属性来检查浏览器功能。
文档
未在Worker中定义,此时您实际上无法在Web工作人员中创建 Document
实例。 JQuery没有为此做好准备 - 你可以在你的问题评论中看到,似乎没有人理解你在没有DOM的情况下对JQuery做什么。
tl;dr: include this script before jQuery
JQuery initally accesses lots of document
properties to check for browser features. document
is not defined in Worker and you actually cannot create Document
instance in web workers at this moment. JQuery isn't prepared for that - as you could see in comments on your question, nobody seems to understand what would you do with JQuery without DOM.
因为我说,JQuery需要 document
来初始化,我创建了一个虚假的伪造文档对象。该对象在JQuery测试期间充当真实文档:
Since, as I said, JQuery needs document
to initialise, I created a dummy fake document object. This object acts as real document during JQuery tests:
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;};
请注意,这个假文档只是为了允许加载jQuery,它不会允许任何真实的DOM操作。
Beware that this fake document is only meant to allow jQuery to load, it won't allow any real DOM operations.
importScripts("workerFakeDOM.js");
importScripts('jquery-2.1.4.min.js');
console.log("JQuery version:", $.fn.jquery);
测试脚本
允许您使用脚本尝试各种版本的JQuery。
Test script
Allows you to try various versions of JQuery with my script.
检查您是否使用 http://
,我的域名与 https://
不兼容。
Check that you're using http://
, my domain doesn't work with https://
.
这篇关于如何在HTML 5 web worker中访问jQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!