1. 程式人生 > >jsonp 動態創建script

jsonp 動態創建script

baidu 哪裏 fun rtb window 動態創建 chan read complete

function loadScript(url, func) {
  var head = document.head || document.getElementByTagName(‘head‘)[0];
  var script = document.createElement(‘script‘);
  script.src = url;

  script.onload = script.onreadystatechange = function(){
    if(!this.readyState || this.readyState==‘loaded‘ || this.readyState==‘complete‘){
      func();
      script.onload = script.onreadystatechange = null;
    }
  };

  head.insertBefore(script, 0);
}
window.baidu = {
  sug: function(data){
    console.log(data);
  }
}
loadScript(‘http://suggestion.baidu.com/su?wd=w‘,function(){console.log(‘loaded‘)});
//我們請求的內容在哪裏?
//我們可以在chorme調試面板的source中看到script引入的內容

jsonp 動態創建script