2

I have some inline jquery what I want to load in the footer after the jquery is loaded.

I do not want to load the jquery in the header. And I do not want to change the inline jquery to a js file because there is also PHP in it.

But I do believe it is possible with javascript to load it in the footer.

In the header you do

var code = [];

So now you have an empty array.

And now I want to push the inline jQuery code in the array.

$(function myFunction(){
    // jQuery methods...
});

So eventually you can do something like this:

code.push(myFunction);

So that I can push all the different jQuery functions and when I put the push code in the footer it will be loaded.

But this does not work for me. The console log says that "myFunction" is not defined...

Jeroen
  • 91
  • 1
  • 11

2 Answers2

2

As I understood, you can do it like this:

var code = [];

function _dom_ready() {
    $(function() {
        // do something here...
    })
}

code.push(_dom_ready);

Or something like this:

function click_something() {
    $('div.something').click(function() {
        // event handler here
    });
}

code.push(click_something);

function click_handler_something2() {
    // event handler here
}

function click_something2() {
    $('div.something2').click(click_handler_something2);
}

code.push(click_something2);

Then run all the functions:

for(var f = 0; f < code.length; f++) {
    if(typeof code[f] == 'function') {
        code[f]();
    }
}
Zlatan Omerović
  • 3,863
  • 4
  • 39
  • 67
  • 1
    I understood it like this too but just be aware [Why is using “for…in” with array iteration such a bad idea?](http://stackoverflow.com/questions/500504/why-is-using-for-in-with-array-iteration-such-a-bad-idea) – A. Wolff Feb 02 '16 at 11:17
  • @A.Wolff Didn't knew that one. Thanks. I'll correct my loop statement. – Zlatan Omerović Feb 02 '16 at 11:19
0
$(function myFunction(){
    // jQuery methods...
});

Here you have a function expression which you are passing as an argument to $.

Consequently:

  • It will be called on the DOM Ready event (because $(a_function) is shorthand for $(document).on('ready', a_function).
  • It creates a variable called myFunction inside the scope of that function.

code.push(myFunction); will work, but only inside myFunction, and you probably don't want it there as it will get pushed onto the array repeatedly every time you call it.

You need a function declaration to make the function appear in the current scope.

function myFunction(){
    // jQuery methods...
}

code.push(myFunction);
$(myFunction);
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335