I want to dynamically include a script tag in a webpage however I have no control of it's src so src="source.js" may look like this.
document.write('<script type="text/javascript">')
document.write('alert("hello world")')
document.write('</script>')
document.write('<p>goodbye world</p>')
Now ordinarily putting
<script type="text/javascript" src="source.js"></script>
in the head works fine but is there any other way I can add source.js dynamically using something like innerHTML?
the only way to do this is to replace
document.write
with your own function which will append elements to the bottom of your page. It is pretty straight forward with jQuery:If you have html coming to document.write in chunks like the question example you'll need to buffer the
htmlToWrite
segments. Maybe something like this:a nice little script I wrote to load multiple scripts:
usage:
You can use the
document.createElement()
function like this:You can try following code snippet.
Well, there are multiple ways you can include dynamic javascript, I use this one for many of the projects.
You can call create a universal function which can help you to load as many javascript files as needed. There is a full tutorial about this here.
Inserting Dynamic Javascript the right way