Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 754
Ian Avatar asked Mar 06 '11 03:03

Ian


People also ask

How do you add a script to a head tag?

To include an external JavaScript file, we can use the script tag with the attribute src . You've already used the src attribute when using images. The value for the src attribute should be the path to your JavaScript file. This script tag should be included between the <head> tags in your HTML document.

How do I run an innerHTML script?

To run script elements inserted with innerHTML with JavaScript, we append the script element to the body element. const script = document. createElement("script"); script. innerHTML = 'console.


1 Answers

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.

like image 130
Marc B Avatar answered Sep 27 '22 18:09

Marc B