General developer forum

Local plugin javascript stops working randomly

 
Me
Local plugin javascript stops working randomly
 

I have built a local plugin where i defined a js file.
I defined it according to the AMD syntax and it worked for some time, i have the source file in my plugins "amd/src" folder and a minified version (which i minified using an online tool) in the "amd/build" folder.
The plugin is active in every page on the site but for some reason in a random way, i sometimes see in the console a
"TypeError: define(...) is not a function" pointing to my define line in my javascript file.
This happens randomly when i refresh/clear cache/clear all moodle caches and i just don't understand why.
Could this be connected to the way i minified the file?

My moodle version is 3.2.1 and i am currently running with debug mode turned on.

 
Average of ratings: -
Picture of Mark Sharp
Re: Local plugin javascript stops working randomly
Core developersParticularly helpful MoodlersPlugin developers

It may be down to how you are calling it. Are you using something like 

$PAGE->requires->js_call_amd('local_plugin/myplugin', 'init');

in your lib.php. Where in your lib.php file is that being called?

Some functions like 

local_myplugin_extend_navigation()

get called automatically, and are a good place to put this kind of call.

 
Average of ratings: -
Me
Re: Local plugin javascript stops working randomly
 

I am indeed using the $PAGE->requires->js_call_amd function to call my js file.
The call is in a function that is triggered by an event.
I have registered it as callback to an event observer in my "events.php" file, that fires on the "\core\event\course_viewed" event.
wouldn't putting it in an extend_navigation function negate my functionality?

 
Average of ratings: -
Picture of Mark Sharp
Re: Local plugin javascript stops working randomly
Core developersParticularly helpful MoodlersPlugin developers

An event seems like an odd place to run javascript, they can and do run in background (e.g. user enrolment via cohort_sync in cron).

The reason you're getting the error is because in the context it's running requirejs hasn't been loaded - and that's probably related to it being in a context where it isn't usually loaded anyway.

By adding it to the navigation you could perhaps use javascript to in effect capture the course_viewed event, by using something like:

if($('body').hasClass('.path-course-view')) {
    // do something
}
 
Average of ratings: -