如何使用DOMDocument将脚本添加到HTML5

Ian*_*Ian 4 php html5 domdocument

a)我是否正确地假设HTML5中的脚本格式正确<script src="script.js"></script>

b)如何使用DOMDocument实现正确的结果?

$domImplementation = new \DOMImplementation ();     

$docType = $domImplementation->createDocumentType ( 'html', '', '' );       

$document = $domImplementation->createDocument ( 'http://www.w3.org/1999/xhtml', 'html', $docType );

$head = $document->createElement ( 'head' );

$script = $document->createElement ( 'script', '' );

$script->setAttribute ('src', 'script.js');

$head->appendChild ( $script );
Run Code Online (Sandbox Code Playgroud)

产生

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

  <head>

    <script src="script.js"/>
Run Code Online (Sandbox Code Playgroud)

HTML5验证器说

/>在非void HTML元素上使用的自闭语法().忽略斜杠并将其视为开始标记.

Mar*_*c B 5

Javascript标记,即使它们通过src=属性加载外部文件,也不能自动关闭.您可能需要向正在创建的DOM元素添加一些非空内容,以强制它非自行关闭.具有单个空格的textnode可以.

  • 作为参考,添加一个完全空的文本节点即可完成这项工作,甚至不需要其中有空格。 (2认同)