Snippets/Load JS and CSS by URL

From MediaWiki.org
Jump to: navigation, search
How to use Snippets
List of Snippets
Crystal Clear action run.png
Load JS and CSS by URL
Language(s): javascript
Compatible with:

MediaWiki 1.19+ 

Description[edit]

Adds support for loading a script or stylesheet from a wiki page in the MediaWiki namespace, based on a URL parameter. This makes showing demonstrations easier as users don't have to enable a gadget or put something in their user common.js.

Code[edit]

/**
 * @source www.mediawiki.org/wiki/Snippets/Load_JS_and_CSS_by_URL
 * @rev 5
 */
mw.loader.using( ['mediawiki.util', 'mediawiki.notify'], function () {
        // CSS
        var extraCSS = mw.util.getParamValue( 'withCSS' );
        if ( extraCSS ) {
                if ( extraCSS.match( /^MediaWiki:[^&<>=%#]*\.css$/ ) ) {
                        importStylesheet( extraCSS );
                } else {
                        mw.notify( 'Only pages from the MediaWiki namespace are allowed.', { title: 'Invalid withCSS value' } );
                }
        }
 
        // JS
        var extraJS = mw.util.getParamValue( 'withJS' );
        if ( extraJS ) {
                if ( extraJS.match( /^MediaWiki:[^&<>=%#]*\.js$/ ) ) {
                        importScript( extraJS );
                } else {
                        mw.notify( 'Only pages from the MediaWiki namespace are allowed.', { title: 'Invalid withJS value' } );
                }
        }
} );

Load multiple files[edit]

/*
 * Load CSS and JS files temporarily through URL.
 * &use=File1.css|File2.css|File3.js
 *
 * @source www.mediawiki.org/wiki/Snippets/Load_JS_and_CSS_by_URL#Load_multiple_files
 * @rev 5
 */

mw.loader.using( ['mediawiki.util'], function () {
        var files = mw.util.getParamValue( 'use' ), user, FileRE;

        if ( !files ) {
                return;
        }

        user = $.escapeRE( mw.config.get( 'wgUserName', '' ) );
        FileRE = new RegExp( '^(?=MediaWiki:' + ( user ? '|User:' + user + '/' : '' ) + ').*\\.(js|css)$' );

        $.each( files.split( '|' ), function(k, v) {
                var f = $.trim( v ), what = FileRE.exec( f ) || ['', ''];
                switch ( what[1] ) {
                        case  'js': importScript(f); break;
                        case 'css': importStylesheet(f); break;
                }
        });
});