习惯<script type="text/template">
tag for client-side processing不足以满足我的目的,因为it isn't nestable。所以我试图扩展它以解决这个限制。
基本上我有一些带有嵌入式图像的原始html,我想用javascript解析内容客户端。我喜欢脚本标记,因为浏览器不会加载其中的图像。但是当html包含脚本标记时,它们会破坏我的应用程序。这是我试图扩展标签的方式:
<script>
var scriptData = document.registerElement('script-data', {
prototype: HTMLScriptElement.prototype
});
captureStart();
</script>
执行时,chrome会抛出以下错误:
Uncaught NotSupportedError: Failed to execute 'registerElement' on 'Document': Registration failed for type 'script-data'. The prototype is already in-use as an interface prototype object.
更新
争议我的意图或建议替代方法很好,但我仍然想要回答我的初步问题:如何扩展脚本标记?
我如何使用它实际上更复杂。我基本上用它来“捕获”我的HTML文档的整个主体,这样我就可以在显示之前操作它们。我知道,这是非常规的。但我正在探索它作为一种学术研究。
这种方法的好处包括:
这种方法面临的挑战包括:
我提出的解决这些问题的方法:
这是一个更大的代码示例:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Script Test</title>
<style>
html, body {
margin: 0;
padding: 0;
}
</style>
<script>document.write("<script type='text/html' id='text-html'>");</script>
</head>
<body>
<img src="http://placehold.it/600x400" alt="" width="600" height="400"/>
</body>
</html>
<!--</script>
<script>
var content = document.getElementById("text-html");
document.write(content.innerHTML);
content.parentNode.removeChild(content);
</script>-->
答案 0 :(得分:0)
简答:使用Object.create()
作为原型对象。以下代码允许您扩展script
元素,并表示document.registerElement()
的使用方式。
var scriptData = document.registerElement('script-data', {
prototype: Object.create(HTMLScriptElement.prototype);
});
请考虑原始代码的这种变体:
var scriptDataProto = HTMLScriptElement.prototype;
// The next statement throws a DOMException of type "NotSupportedError".
var scriptData = document.registerElement('script-data', {
prototype: scriptDataProto
});
此处说明了异常的来源:
scriptDataProto === HTMLScriptElement.prototype; // true
您提供了对HTMLScriptElement.prototype
的引用,这意味着您要将完全相同的原型用于您正在创建的自定义脚本元素。它还没有很好地记录,但你提供的原型不能作为任何内置HTML[*]Element
原型的参考;你必须提供一个新的原型对象。
如果您想继承<script>
代码的原型,那么您必须使用{{创建一个新的原型对象,并继承自HTMLScriptElement.prototype
1}}。
Object.create()
如果您愿意,可以在不影响基础var scriptDataProto = Object.create(HTMLScriptElement.prototype);
scriptDataProto === HTMLScriptElement.prototype; // false
的情况下向此原型添加新成员。
HTMLScriptElement.prototype
为了进一步阅读,HTML5 Rocks has a well-written article确实帮助我理解了自定义元素的工作原理。