1

I am using this amazing script, waitForKeyElements() (wfke), which helps dealing with dynamically loaded content in userscripts.

It does a perfect job, but I am having a lot of trouble pre-calculating some variables, and then using that when wfke executes.

Basically, It is correctly running hundreds of times for a list of nodes, that all get loaded right away (after the page is loaded). But I cannot be creating expensive variables and doing expensive calculations for every single item in this list. So I try to do these outside of the wfke function.

As you can see in the following example, I have tried two different ways to pre-set the variable "icons", both do not work. I am guessing this is probably a feature of @require scripts? Would copy-pasting the script into my main script fix the issue? Would that be the only way?

// @require         https://gist.github.com/raw/2625891/waitForKeyElements.js
var icons = $('some stuff');
//Run for every BOX element that gets loaded by ajax
waitForKeyElements(".box", main);

function main(jqnode){
  if (typeof icons === 'undefined') { //icons is undefined here, and will be again the next time this function is run.
  var icons = $('some stuff');
  }
 jqnode.append(icons);
}

In Chrome, Tampermonkey (beta)

Brock Adams
  • 90,639
  • 22
  • 233
  • 295
Jonathon
  • 2,571
  • 5
  • 28
  • 49

1 Answers1

1

Refer to JavaScript Scoping and Hoisting and to "Surprised that global variable has undefined value in JavaScript".

When you do this:

var icons = $('some stuff');

anywhere within the function main() scope, it creates a local variable that is used in place of the global-scope variable. This function-scope variable is undefined at the time of the if() statement.

Also, the question is not clear; I assume you want to copy the icons to all .box nodes? The code is currently structured to have only one set of icons and to move them to whatever .box appears last.

If you want a copy, use jQuery's .clone() method. Something like:

// @require  https://gist.github.com/raw/2625891/waitForKeyElements.js

var icons = $('some stuff');

//Run for every BOX element that gets loaded by ajax
waitForKeyElements (".box", main);

function main (jqnode){
    jqnode.append (icons.clone () );
    /*-- Or use this to copy event handlers, but should be using 
        `.on()` instead, anyway.

    jqnode.append (icons.clone (true) );
    */
}


If that is not what you want, clarify and specify.

Community
  • 1
  • 1
Brock Adams
  • 90,639
  • 22
  • 233
  • 295