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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With