2012-01-14 20 views
3

我開始在Opera中學習UserJS。爲了測試,我試圖連接jQuery庫和jQuery UI,但它不起作用。這裏是代碼:Opera中的jQuery用戶jS

(function() { 
    var headID = document.getElementsByTagName("head")[0];   
    var newScript = document.createElement('script'); 
    newScript.type = 'text/javascript'; 
    newScript.id = 'myjQuery'; 
    newScript.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js'; 
    headID.appendChild(newScript); 

    newScript = document.createElement('script'); 
    newScript.type = 'text/javascript'; 
    newScript.id = 'myjQuery2'; 
    newScript.src = 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js'; 
    headID.appendChild(newScript); 

    alert('first alert'); 
    window.addEventListener('load', function (e) { 
     $('body').html('test page'); 
    }, false); 
})(); 

第一警報工作。兩個庫連接到頁面,但jQuery代碼不起作用。哪裏不對?

PS。我收到一個錯誤:ReferenceError:Undefined variable:$

回答

2

你的腳本是異步加載的,並且在頁面加載時可能還沒有準備好,因此$/jQuery在窗口範圍中不存在。

由於您使用jQuery,您可以輕鬆使用它的$(document).ready()或$(),因爲它在頁面加載後調用時也可以使用。

下面是與觸發一個簡單script.onload處理器小提琴jQuery的ready(),一旦這兩個腳本可用: http://jsfiddle.net/qaYJF/

+0

我想這一點,但沒有奏效。你確定這個選項有效嗎? – Anton 2012-01-14 12:56:00

+0

我正在寫Opera擴展。這是你的擴展方法,它沒有工作:http://dl.dropbox.com/u/30086473/HabraCorrector.oex – Anton 2012-01-14 12:58:31

+0

請看看,並告訴我有什麼問題 – Anton 2012-01-14 12:58:52