ResourceLoader是MediaWiki的核心模块加载系统,它负责高效地加载JavaScript、CSS和其他资源。通过ResourceLoader,可以方便地将jQuery插件集成到MediaWiki中。
首先需要创建一个MediaWiki扩展,目录结构如下:
MyExtension/
├── extension.json
├── resources/
│ ├── myPlugin.js
│ └── myPlugin.css
└── MyExtension.php
在extension.json
中定义资源:
{
"name": "MyExtension",
"version": "1.0.0",
"author": "Your Name",
"url": "https://www.example.com",
"descriptionmsg": "myextension-desc",
"license-name": "GPL-2.0-or-later",
"type": "other",
"ResourceModules": {
"ext.myExtension": {
"scripts": ["resources/myPlugin.js"],
"styles": ["resources/myPlugin.css"],
"dependencies": ["jquery"],
"messages": [],
"targets": ["desktop", "mobile"]
}
},
"manifest_version": 2
}
在PHP文件中加载模块:
class MyExtension {
public static function onBeforePageDisplay( OutputPage &$out, Skin &$skin ) {
$out->addModules( 'ext.myExtension' );
}
}
在resources/myPlugin.js
中:
( function( $, mw ) {
'use strict';
// 定义jQuery插件
$.fn.myPlugin = function( options ) {
var settings = $.extend( {
color: 'red',
backgroundColor: 'white'
}, options );
return this.each( function() {
$( this ).css( {
color: settings.color,
backgroundColor: settings.backgroundColor
} );
} );
};
// 页面加载完成后初始化插件
$( function() {
$( '.my-plugin-element' ).myPlugin( {
color: 'blue',
backgroundColor: '#f0f0f0'
} );
} );
// 或者通过mw.hook在特定事件后执行
mw.hook( 'wikipage.content' ).add( function( $content ) {
$content.find( '.my-plugin-element' ).myPlugin();
} );
} )( jQuery, mediaWiki );
原因:
解决:
extension.json
中的路径是否正确原因:
$
而未考虑MediaWiki的noConflict模式解决:
jQuery
对象原因:
解决:
extension.json
中添加targets: ["desktop", "mobile"]
$out->addModules()
时考虑编辑器上下文mw.loader.using()
按需加载mw.loader.using( 'ext.myExtension' ).then( function() {
// 插件加载完成后执行
$( '#myElement' ).myPlugin();
} );
mw.hook( 'ext.myExtension.loaded' ).add( function( plugin ) {
// 其他模块可以使用这个钩子访问插件功能
} );
通过ResourceLoader添加jQuery插件是MediaWiki扩展开发中的常见需求,遵循上述方法可以确保插件高效、稳定地运行,并与MediaWiki生态系统良好集成。
没有搜到相关的文章