I'm having problems getting this to work. I first tried setting my script tags as strings and then using jquery replaceWith() to add them to the document after page load:
var a = '<script type="text/javascript">some script here</script>'; $('#someelement').replaceWith(a);
But I got string literal errors on that var. I then tried encoding the string like:
var a = '&left;script type="text/javascript">some script here<\/script>';
but sending that to replaceWith()
outputs just that string to the browser.
Can someone please let me know how you would go about dynamically adding a <script>
tag into the browser after page load, ideally via jQuery?
Scripts can be placed in the <body> , or in the <head> section of an HTML page, or in both.
For anyone still trying to do this, no, you can't inject a script using innerHTML , but it is possible to load a string into a script tag using a Blob and URL.
To execute JavaScript in a browser you have two options — either put it inside a script element anywhere inside an HTML document, or put it inside an external JavaScript file (with a . js extension) and then reference that file inside the HTML document using an empty script element with a src attribute.
We can include the jQuery CDN URL in the script tag and use jQuery in HTML. We can either write the jQuery in a separate . js file and include it in the HTML file or write the jQuery inside the script tag. First, go to the JQuery CDN website and choose the latest stable version of the jQuery.
You can put the script into a separate file, then use $.getScript
to load and run it.
Example:
$.getScript("test.js", function(){ alert("Running test.js"); });
Try the following:
<script type="text/javascript"> // Use any event to append the code $(document).ready(function() { var s = document.createElement("script"); s.type = "text/javascript"; s.src = "http://scriptlocation/das.js"; // Use any selector $("head").append(s); });
http://api.jquery.com/append
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