为document.createElement('script')设置'src'属性?

时间:2016-08-14 08:49:46

标签: javascript highcharts

我正在尝试在不同的标签上创建高清图。但我得到错误,高图表没有定义。我试图使用不同的方法注册Highchart.js。代码如下。

function OpenWin() {   
  var w = window.open();
  w.document.open();
  w.document.write('<div id="container" style="width:100%; height:400px;"></div>');

  var scriptHead = w.document.createElement("SCRIPT");
  //scriptHead.setAttribute('src','http://code.highcharts.com/highcharts.js');
  var link = "http://code.highcharts.com/highcharts.js";
  scriptHead.src = link;
  w.document.head.appendChild(scriptHead);

  var script = w.document.createElement("SCRIPT");
  w.document.body.appendChild(script);
  var js = w.document.createTextNode('var a = localStorage.getItem("ImportOptions"); console.log(JSON.parse(a)); var chart = new Highcharts.Chart(JSON.parse(a))');
  script.appendChild(js);
  w.document.close();    
}

1 个答案:

答案 0 :(得分:4)

您需要等待以前的脚本加载。 Demo

function OpenWin() {   
  var w = window.open();
  w.document.open();
  w.document.write('<div id="container" style="width:100%; height:400px;"></div>');

  var scriptHead = w.document.createElement("SCRIPT");
  //scriptHead.setAttribute('src','http://code.highcharts.com/highcharts.js');
  var link = "http://code.highcharts.com/highcharts.js";

  // bind on script load event
  scriptHead.onload = function() {
      var script = w.document.createElement("SCRIPT");
      w.document.body.appendChild(script);
      var js = w.document.createTextNode('var a = localStorage.getItem("ImportOptions"); console.log(JSON.parse(a)); var chart = new Highcharts.Chart(JSON.parse(a))');
      script.appendChild(js);
      w.document.close();        
  }

  // as A.Wolff mentioned you might need to set onload befor src for some browsers.
  scriptHead.src = link;
  w.document.head.appendChild(scriptHead);
}