MozTW 討論區
https://forum.moztw.org/

動態匯入 js 檔
https://forum.moztw.org/viewtopic.php?f=13&t=15658
1 頁 (共 1 頁)

發表人:  iameason [ 2006-09-22, 22:01 ]
文章主題 :  動態匯入 js 檔

這是我在 http://csp.no-ip.com/ajax/ 看到的


以下為主程式:
代碼:
function importScript(src) {
  var script = document.createElement("script");
  script.type = "text/javascript";
  script.src = src;
  document.getElementsByTagName("head")[0].appendChild(script);
  }

function a(js) {
  importScript(js);

  b = b * 5;
  document.getElementById("某div").innerHTML = b;
  }


a("1.js");


以下為 1.js 的內容:
代碼:
b = 9;


我的 Web Developer 會一直說 --> 變數b 沒有定義...
可是,如果 1.js 檔有照情況匯入,應該沒問題阿?!
麻煩各位了... :oops:

發表人:  李某人 [ 2006-09-23, 11:41 ]
文章主題 : 

因為 1.js 的內容是加在最後的,粗糙點說會變成這樣:

代碼:
function a(js) {
  importScript(js);

  b = b * 5;
  document.getElementById("某div").innerHTML = b;
  }

b = 9;

b 在定義前就已經被使用了…。

發表人:  iameason [ 2006-09-25, 19:20 ]
文章主題 : 

李某人 寫:
因為 1.js 的內容是加在最後的,


有辦法...放到前面嗎? :oops: 謝謝

發表人:  kourge [ 2006-09-27, 13:27 ]
文章主題 : 

直接在 DOM 內插入一個 <script> 元素在 Safari 下沒有用,所以最好的方法就是用可怕的 document.write()。

發表人:  lch2003 [ 2006-09-27, 21:12 ]
文章主題 : 

kourge 寫:
直接在 DOM 內插入一個 <script> 元素在 Safari 下沒有用,所以最好的方法就是用可怕的 document.write()。


真可怕  :lol:

script.aculo.us 用的方法:
代碼:
var Scriptaculous = {
  Version: '1.6.1',
  require: function(libraryName) {
    // inserting via DOM fails in Safari 2.0, so brute force approach
    document.write('<script type="text/javascript" src="'+libraryName+'"></script>');
  },
  load: function() {
    if((typeof Prototype=='undefined') ||
       (typeof Element == 'undefined') ||
       (typeof Element.Methods=='undefined') ||
       parseFloat(Prototype.Version.split(".")[0] + "." +
                  Prototype.Version.split(".")[1]) < 1.5)
       throw("script.aculo.us requires the Prototype JavaScript framework >= 1.5.0");
   
    $A(document.getElementsByTagName("script")).findAll( function(s) {
      return (s.src && s.src.match(/scriptaculous\.js(\?.*)?$/))
    }).each( function(s) {
      var path = s.src.replace(/scriptaculous\.js(\?.*)?$/,'');
      var includes = s.src.match(/\?.*load=([a-z,]*)/);
      (includes ? includes[1] : 'builder,effects,dragdrop,controls,slider').split(',').each(
       function(include) { Scriptaculous.require(path+include+'.js') });
    });
  }
}

Scriptaculous.load();

發表人:  iameason [ 2006-09-27, 21:45 ]
文章主題 : 

感謝三位..!!
試過了再來跟大家報告... :o

1 頁 (共 1 頁) 所有顯示的時間為 UTC + 8 小時
Powered by phpBB® Forum Software © phpBB Group
https://www.phpbb.com/