How to use DOMDocument to add script in HTML5

a) Do I correctly assume that the correct format for the script in the HTML5 header is <script src="script.js"></script> ?

b) How to achieve the correct result using 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"/> 

HTML5 validator says

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

+4
source share
1 answer

Javascript tags, even if they load an external file using the src= attribute, cannot be closed by themselves. You may need to add non-empty content to the generated DOM element to prevent it from closing itself. A text block with one space will do.

+5
source

Source: https://habr.com/ru/post/1342475/


All Articles