要使用require JS,您需要外接程序头
<!-- Delayed execution of inline jQuery scripts with ready waiting event -->
<script type="text/javascript">(function(w, d, u){w.readyQ = []; w.bindReadyQ = []; function p(x, y){if (x == "ready"){w.bindReadyQ.push(y); } else{w.readyQ.push(x); }}; var a = {ready:p, bind:p}; w.$ = w.jQuery = function(f){if (f === d || f === u){return a} else{p(f)}}})(window, document)</script>
<!-- Loading require.js -->
<script async data-main="/wp-content/theme/default/js/requirejs.config" src="/wp-content/theme/default/js/requirejs.min.js"></script>
接下来,创建Require。JS配置文件和更新函数。php
/* Delayed loading of all JS files */
add_filter(\'script_loader_tag\', function($tag, $handle, $src) {
if (isAdmin()) return $tag;
if (stripos($src, \'jquery.min\') !== FALSE) return \'\';
global $wp_scripts;
$dependencies = $wp_scripts->query($handle, \'registered\')->deps;
$dependenciesList = empty($dependencies) ? "\'jquery\'" : "\'" . implode("\',\'", $wp_scripts->query($handle, \'registered\')->deps) . "\'";
return "<script>$(document).ready(function(){ define(\'{$handle}\', [{$dependenciesList}], function(){require([\'{$src}\']);}); require([\'{$handle}\']); });</script>\\n";
}, 10, 3);
在finish中,您需要在配置文件中添加延迟jquery事件的初始化,如下所示:
requirejs.config({
paths: {
jquery: \'jquery.min\'
}
});
//loading jquery as dependency
require(["jquery"], function ($) {
(function($,d){$.each(readyQ,function(i,f){$(f)});$.each(bindReadyQ,function(i,f){$(d).bind("ready",f)})})(jQuery,document);
});