Inserting Script Tags into HTML Documents in JavaScript
To dynamically add script tags to your HTML document, you can leverage the appendChild() method or jQuery's append(). However, directly appending script tags may result in the content being stripped out.
Using document.createElement()
To overcome this issue, you can create the script tag using document.createElement(), and then manually set the HTML content using script.innerHTML. Finally, append the script element to the head or body of the document:
// Create the element var script = document.createElement("script"); // Add script content script.innerHTML = "..."; // Append document.head.appendChild(script);
Alternatively, you can append to the body:
document.body.appendChild(script);
Using jQuery
If you're using jQuery, you can append the script element using the append() method:
// Create the element var script = $("<script>").html("..."); // Append $("head").append(script);
This method simplifies the process by automatically creating the script tag and handling the content insertion.
The above is the detailed content of How to Insert Script Tags into HTML Documents Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!