xeyownt / mwpgnjs

A MediaWiki extension to display and animate chess games (boards and moves) given in PGN format
Apache License 2.0
3 stars 1 forks source link

Can't load PgnViewerJS with MediaWiki ResourceLoader #1

Closed xeyownt closed 6 years ago

xeyownt commented 6 years ago

Ideally CSS & JS scripts must be loaded with MediaWiki ResourceLoader. Here a summary of things I tried.

Tried to import from LocalSettings.php using ResourceLoader.

    // register a ResourceLoader module...
    $wgResourceModules['custom.foo.whatever'] = array(
        'scripts' => array( 'extensions/PgnJS/js/pgnvjs.js' ),
        // could e.g. add dependencies on core modules here
    );

    // ...and set up a hook to add it to every page
    function addMyCustomScripts( &$out ) {
        $out->addModules( 'custom.foo.whatever' );
        return true;
    }
    // $wgHooks['BeforePageDisplay'][] = 'addMyCustomScripts';

This does not work. Apparently the JS script is embeded in some kind of lambda expression in a mw loader call whatever thingy.

Found a working hack on Stackoverflow. Add to LocalSettings.php:

    # Add onBeforePageDisplay function to BeforePageDisplay Hook
    $wgHooks['BeforePageDisplay'][] ='onBeforePageDisplay';

    function onBeforePageDisplay( OutputPage &$out, Skin &$skin )
    {
        $script = '<script type="text/javascript" src="http://localhost/PgnViewerJS/dist/js/pgnvjs.js"></script>';
        $out->addHeadItem("itemName", $script);
        return true;
    };

I added the hook to the extension, and this works.

This must be a temporary solution only since now JS is added to all wiki pages. The SO page linked above contains many useful information on linking in a JS script. Maybe the solution is there.

xeyownt commented 6 years ago

PgnViewerJS embeds a copy of JQuery, but MediaWiki already has JQuery loaded. But apparently JQuery is only available when loaded via ResourceLoader. When loaded with addHeadItem, we get in browser console:

ReferenceError: jQuery is not defined [Learn More]               pgnvjs.js:14:3
xeyownt commented 6 years ago

50 browser tabs later about learning on MediaWiki, Javascript, Node.js and whatever, I have some explanations about the issues:

As a result, I went for the following solution: