Search code examples
phphtmldomdocument

How to use DOMDocument to add script to HTML5


a) Am I right in assuming the correct format for script in head in HTML5 is <script src="script.js"></script>?

b) How do I achieve the correct result using the 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 );

produces

<!DOCTYPE html>

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

  <head>

    <script src="script.js"/>

The HTML5 validator says

Self-closing syntax (/>) used on a non-void HTML element. Ignoring the slash and treating as a start tag.


Solution

  • Javascript tags, even if they're loading an external file via the src= attribute, can't be self closing. You may need to add some non-empty content to the DOM element you're creating to force it to be non-self closing. A textnode with a single space would do.