2014-01-05 29 views
0

我想寫一個書籤,它將從URL捕獲一些參數並將其發送到腳本(該帖子中的URL只是一個虛擬的atm)。加載jQuery外部的書籤

問題是,我嘗試將jQuery添加到頁面中,以便稍後使用$ .post。當試圖運行書籤我在控制檯中出現以下錯誤:

Uncaught ReferenceError: $ is not defined 

我可以看到jQuery是成功地通過查看瀏覽器中的元素標籤附加。有關如何解決此問題的任何提示?

你可以看到下面的書籤:

javascript: 

function appendScript() { 
    var head = document.getElementsByTagName("head")[0]; 
    var script = document.createElement("script"); 
    script.src = "http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"; 
    head.appendChild(script); 

} 

appendScript(); 

function parseUri (str) { 
    var o = parseUri.options, 
     m = o.parser[o.strictMode ? "strict" : "loose"].exec(str), 
     uri = {}, 
     i = 14; 

    while (i--) uri[o.key[i]] = m[i] || ""; 

    uri[o.q.name] = {}; 
    uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) { 
     if ($1) uri[o.q.name][$1] = $2; 
    }); 

    return uri; 
}; 

parseUri.options = { 
    strictMode: false, 
    key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"], 
    q: { 
     name: "queryKey", 
     parser: /(?:^|&)([^&=]*)=?([^&]*)/g 
    }, 
    parser: { 
     strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)[email protected])?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/, 
     loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)[email protected])?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/ 
    } 
}; 

couponCode = parseUri(window.location.search).queryKey['couponCode']; 
customerId = parseUri(window.location.search).queryKey['customerId']; 

function showModal() { 
    if (couponCode != null) { 
     alert("Here is your coupon. Make sure to use it at checkout!" + couponCode); 
    } 
} 

showModal(); 

function parakeetCommunicator() { 

    if (couponCode != null) { 
     console.log("Sending data to Parakeet..."); 

     $.post("http://test.com/datascript.go", { customerId: customerId, couponCode: couponCode }) 
      .done(function(data) { 
       console.log("Succesfully posted the coupon was viewed to Parakeet server."); 
      }); 
     } 
} 

parakeetCommunicator(); 

回答

2

腳本異步地加載,你可以使用腳本e.g的onload事件解決這個問題:

var script = document.createElement("script"); 
script.onload = parakeetCommunicator; 
script.src = ...; 

,並刪除其他調用此方法。

如果你只需要jQuery的相對Ajax調用,你應該在建立自己的jQuery版本只支持這些方法interrested,請參閱:http://projects.jga.me/jquery-builder/

+0

完美的感謝! – user2656127