RadiantHeart
RadiantHeart

Reputation: 266

Using jQuery within Opera User JavaScript

I wonder if it's possible to load jQuery within Opera User JavaScript, so that I can use jQuery functionality in it, even on pages that are not currently using jQuery.

Upvotes: 9

Views: 3169

Answers (3)

BananaAcid
BananaAcid

Reputation: 1

Just for completeness:

I use it regularly with my userJS. Just copy your jquery.js into your userJS folder.

Option 1:

to keep it from conflicting with available jquery, use the noConflict option within the jqueryfile and associate jQuery with with your own identifier (jQueryMyIdentifier = jQuery; jQuery = null;) . your JS code can be wrapped with

(function($) {
    // normal jquery js based on, jQueryMyIdentifier
    $('#bla').x();
})(jQueryMyIdentifier);

Option 2:

check out, how to include a remote js using javascript. implement that include line into your JS.

include "http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"

or alike.

Upvotes: 0

Sk8erPeter
Sk8erPeter

Reputation: 6987

I just wrote an Opera userJS, which I transformed from a Google Chrome extension, where jQuery could easy be loaded, but here in Opera I had to use another solution, and I wanted to make minimal changes in my code.

I just append a new script tag in the document's header with a working jQuery source. It starts to get downloaded BEFORE DOM is ready.

This is my working solution, hope that helps!

// ==UserScript==
// @name This is the name of my userJS
// @description That's the description of my userJS
// @include http://blahblah.hu/*
// @include http://*.blahblah.hu/*
// @match http://blahblah.hu/*
// @match http://*.blahblah.hu/*
// @version 1.0
// ==/UserScript==

(function( ) {

    // include jQuery
    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.5.1/jquery.min.js';
    headID.appendChild(newScript);

    window.addEventListener('load', function (e)  {

        // you can write your jQuery code now!
        $('#yourElementId').css('background-color', 'yellow');

        // further jQuery codes
        // ...

    }, false);

})( );

Upvotes: 8

DisgruntledGoat
DisgruntledGoat

Reputation: 72510

Well it would certainly be possible if you paste the whole lot of jQuery into your UserJS file, or perhaps create a separate UserJS file for all pages with the jQuery library. However, there's a possibility that it would conflict with any pages using jQuery.

Depending on your requirements, maybe you could roll your own mini-framework? For example some simple functions to grab elements by tag/class/id:

function $id(id) {
  return document.getElementById(id);
}

Note: you may get a better response over at Opera's forums.

Upvotes: 3

Related Questions