Search code examples
javascriptjqueryjquery-uigreasemonkeyuserscripts

Inserting jQuery and jQuery UI into header with userscript


I've been having trouble trying to insert jQuery and jQuery UI into webpage headers through a Greasemonkey userscript I'm working on. Here's how I'm inserting it:

var ccst1 = document.createElement("script");
ccst1.id = "ccst1";
ccst1.src = "http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js";
ccst1.type = "text/javascript";
document.head.appendChild(ccst1);
var ccst2 = document.createElement("script");
ccst2.id = "ccst2";
ccst2.src = "https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js";
ccst2.type = "text/javascript";
document.head.appendChild(ccst2);

The actual insertion process works, but when I've inserted it, using jQuery on the page (e.g. in an html onclick) works, but jQuery UI immediately gives me a "$ is not defined" error AND a "jQuery is not defined" error the second it's inserted. No jQuery UI then works on the page.


Solution

  • I've just found a solution to this. It actually did have to do with jQuery not being loaded properly, but none of the other solutions worked for me. Joey Geralnik suggested this, which is working properly:

    var ccst1 = document.createElement("script");
    ccst1.id = "ccst1";
    ccst1.src = "http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js";
    ccst1.type = "text/javascript";
    document.body.appendChild(ccst1);
    function ccst2func() {
        var ccst2 = document.createElement("script");
        ccst2.id = "ccst2";
        ccst2.src = "https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js";
        ccst2.type = "text/javascript";
        document.body.appendChild(ccst2);
        ccst2.addEventListener("load", ccst4func, true);
    }
    ccst1.addEventListener("load", ccst2func, true);
    
    document.body.insertBefore(concealerPanel, document.body.firstChild);
    
    function ccst4func() {
        var ccst4 = document.createElement("script");
        ccst4.id = "ccst4";
        ccst4.type = "text/javascript";
        ccst4.innerHTML = "$('#ccpanelmassiveconstruct').draggable({'handle': '#ccpmchandle', 'constrain': 'parent', 'distance': 20, 'cursor': 'move', 'grid': [10,10], 'scroll': true});\n$('#iframeDragger').resizable();\n$('#ccpmctabs').tabs();";
        document.body.appendChild(ccst4);
    }