Desvincular eventos agregados por un script externo cargado con la función getScript de jQuery

I am loading an external script using jQuery's $.getScript function and it has something in it which I cannot understand:

if (!!window.addEventListener){ // FF
    window.addEventListener('load', init, false);
} else if (!!window.attachEvent){ // IE
    window.attachEvent('onload', init);
} else {
    window.onclick = init;

Can someone please explain what this does?

I'm not sure but it adds some event listeners to check that the page is loaded.

But since I am loading the script with $.getScript function, I don't need those listeners anymore.

Is there a way to unbind them in the callback of the $.getScript function?

preguntado el 27 de noviembre de 13 a las 01:11

1 Respuestas

addEventListener adds event handlers, and attachEvent does the same for browsers that doesn't support addEventListener, which is just older IE.

The condition you have checks which one is available, and attaches an event handler to the window.onload event that calls the function init().
If none of the regular onload handler are available, it falls back to calling the init() function once the window is first clicked.

To remove the function, you'll have to try and do the opposite once the script has loaded.

Dices que estás usando $.getScript, and that has a callback, so something like :

$.getScript('myscript.js', function() {
    if (window.removeEventListener) {
        window.removeEventListener( 'load', init, false );
    }else if ( window.detachEvent ) {
        window.detachEvent( 'onload', init );
        window.onclick = function() {};

of course, it would be much easier and better to just remove the original event handler in the script you're loading if you no longer need that event handler.

respondido 27 nov., 13:01

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.