B. Clay Shannon B. Clay Shannon - 1 year ago 57
Javascript Question

Is it possible to dynamically replace the script section of an html page?

I am starting out a page with some canned/mock data being fed to Chart.JS charts, such as:

data: [2755, 2256, 1637, 1608, 1603, 1433, 1207, 1076, 1056, 1048],

I want to replace that bogus data with real/live data. Can I replace the
part of an html page with what is passed back from an AJAX call?

IOW, can I do something like this:

type: 'GET',
'@Url.RouteUrl(routeName: "QuadrantData"
routeValues: new { httpRoute = true, unit = "un", begdate = "bd", enddate
"ed" })'
.replace("un", encodeURIComponent(_unit))
.replace("bd", encodeURIComponent(_begdate))
.replace("ed", encodeURIComponent(_enddate)),
contentType: 'text/plain',
cache: false,
xhrFields: {
withCredentials: false
success: function (returneddata) {
error: function () {
console.log('error in ajax call t


IOW, instead of:


...or some such, something like this:


Answer Source

I will be adding on to what Travis and other commenters said.

When HTML is being parsed, script tags are executed as soon as the closing script tag is seen. What is left is just a tag with inner text. I will be demonstrating this behavior with below snippet.

script {
  display: block;
  background: white;
  min-height: 100px;
  border: 1px solid black;
  white-space: pre;
  font-size: 13px;
Below scripts counts upward every second. But editing it wont change its after effects.
<script contenteditable="true">
counterInterval = setInterval(function clicked(){

This snippet features a contenteditable script. You can change its contents as you change a textbox. But you will see its effects won't change.

Alternatively, when a new script tag is inserted into the page (e.g. with javascript), it is executed. Below snippet demonstrates this.

reinsertScripts = function() {
  var script = document.querySelector("#reinsert");
  var parent = script.parentNode;
  var nscript = document.createElement("script");
  nscript.contentEditable = true;
  nscript.id = "reinsert";
  nscript.innerHTML = script.innerHTML;

script[contenteditable="true"] {
  display: block;
  background: white;
  min-height: 100px;
  border: 1px solid black;
  white-space: pre;
  font-size: 13px;
<p><span>Count: </span><span id="counter"></span></p>

Below scripts counts upward every second. Clicking reinsert button will rerun the script and you may see changes.
<script contenteditable="true" id="reinsert">
  counter = 0;
  counterInterval = setInterval(function clicked() {
  }, 1000);

<button onClick="reinsertScripts()">Reinsert script</button>

Though this is the answer to your question, I believe this is not the answer you need. Look for "dynamically changing ChartJS data". Basically, you can use chart.addData and chart.removeData functions to update a chart's data.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download