There are lots js based widgets today. For example, web share widget,Google search widget,Comment widget,twitter, facebook, amazon ads... etc. They let you easily add functionality to your site.
If your webpage is static html, or generated by php or content manager software, you can directly include these widgets at the right place at the server side. However, sometimes it is convenient to use a js to insert them. Because, you may want the location of the widget to be different for different pages. Or, only centain pages you want to include the widget, but you don't know which until the page is generated.
So, the solution is to use a client side js that insert these js widgets.
It depends on how you construct the element to be inserted. If the 「<script...>...</script>」 is constructed using 「innerHTML = ...」, then it won't work. But if it is constructed as a DOM element, then it'll work.
Using innerHTML Does Not Work
First, let's see what happens if you don't do anything special.
Suppose you want to use js to insert the following js code.
Suppose you do it this way:
It will fail in IE8, Google Chrome, Opera. (but works in Firefox 3.6.12).
You can see what your browser do here: insert_js.html.For a version where each js file is on its own page, see: js_insert_js.html.
Creating 「<script>」 Object by createElement
Here's how to make it work. It's easy. Instead of using 「myElement.innerHTML="<script>...</script>";」, you should create the “script” element as a DOM object, then you insert this object.
Here's a sample js code:
Here's a test page using this code: js_insert_js_works.html.
Suppose you want to insert this code:
It's a widget that shows a Twitter button with number of tweets of the page.
Here's how you do it in your js:
Thanks to “idealmachine” and DVK. stackoverflow.com.