Reputation: 615
I have a website with a <script>
tag
<script id='text1' type='text/javascript'></script>
that I insert some javascript code into from a <textarea>
<div id="text2">
<textarea class="text3"></textarea>
</div>
while executing some javascript
// get text from text area
obj = document.getElementById('text2').getElementsByClassName('text3');
var text = obj[0].value;
// assign to script tag
obj = document.getElementById('text1');
obj.text = text;
and on a button click it executes a function in a namespace from the <textarea>
code
var namespace1 = {};
(function(context) {
context.getGameName = function() {
return ('text');
};
})(namespace1);
Everything works just fine, but if I attempt to change the text in the <textarea>
and update the contents of the <script>
tag, I can see in the console that the contents in the DOM are being updated, but when executing the code again on the button click, the old code is executed, not the new.
How can I update the javascript and execute the new version of a function with the same name?
Upvotes: 2
Views: 280
Reputation: 114481
A script
tag content is evaluated when the node is first inserted in the DOM, not every time you change its content.
You need to create a new script tag with the new content, remove the old one and insert the new into the DOM.
var s = document.createElement("script");
s.textContent = "console.log('Hello,');"
document.body.append(s); // Will display "Hello," on console
document.body.removeChild(s);
s = document.createElement("script"); // <<-- create a new node
s.textContent = "console.log('world.');"
document.body.append(s); // Will display "world." on console
if you omit the second document.createElement
call the "world."
call will not be done.
Upvotes: 1
Reputation: 446
To define a new version of the function with the same name, just redeclare it (below is one of ways):
var newScript = document.createElement('script');
newScript.innerHTML = document.getElementById('text2').getElementsByClassName('text3')[0].value;
document.body.appendChild(newScript);
You've no need to change the contents of some script tag you've included.
Upvotes: 0