Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically insert a <script> tag via jQuery after page load?

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"&gt;some script here&lt;\/script&gt;'; 

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?

like image 699
Doug Avatar asked Oct 04 '10 18:10

Doug


People also ask

Can I put script tag after body?

Scripts can be placed in the <body> , or in the <head> section of an HTML page, or in both.

Can scripts be inserted with innerHTML?

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.

How do you trigger a script in HTML?

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.

Does jQuery go inside script tag?

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.


2 Answers

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"); }); 
like image 126
Rocket Hazmat Avatar answered Oct 04 '22 04:10

Rocket Hazmat


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

like image 40
Bassem Avatar answered Oct 04 '22 04:10

Bassem