How to run userscript(/greasemonkey) after AngularJS library is loaded

All we need is an easy explanation of the problem, so here it is.

I just want to create some extensions to angular object to make AngularJS debugging more convenient.

But when I run add userscript, it can’t find an angular object. AngularJS library is loaded in the bottom of tag.

UPD: @estus provided right answer, but if you want to use chrome you need to install it via Tampermonkey extension.

You can find final code snippet here.

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

The fact that Angular is unavailable at the moment when user script runs indicates that Angular is loaded asynchronously, this is quite normal for any SPA (also check that @run-at is not set to document-start, it isn’t the desirable behaviour here).

The usual workaround for user scripts is to watch for the desired variable:

var initWatcher = setInterval(function () {
    console.log('watch');
    if (unsafeWindow.angular) {
        clearInterval(initWatcher);
        init();
    }
}, 100);

function init() {
    console.log('angular', unsafeWindow.angular);
}

If cross-browser compatibility is not required, then FF-specific Object.prototype.watch can be used instead:

unsafeWindow.watch('angular', function (prop, oldVal, newVal) {
    console.log('watch');
    if (newVal) {
        unsafeWindow.unwatch('angular');
        // angular is still undefined ATM, run init() a bit later
        setTimeout(init);
    }
    return newVal;
});

function init() {
    console.log('angular', unsafeWindow.angular);
}

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply