I started studying UserJS in Opera. To test, I tried to connect the jQuery library and the jQuery UI, but it did not work. Here's the code:

(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);
})( );

First alert work. Two libraries is connected to page, but jQuery code not working. What is wrong?

PS. I get an error: ReferenceError: Undefined variable: $

有帮助吗?

解决方案

Your scripts are loaded asynchronously and are probably not ready yet when the page has loaded, thus $/jQuery don't yet exist in window scope.

Since you're using jQuery you can easily use it's $(document).ready() or just $(), as it also works when called AFTER the page has loaded.

Here's a fiddle with a simple script.onload handler that fires jQuery's ready() once both scripts are available: http://jsfiddle.net/qaYJF/

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top