Wordpress插件:页面前加载JavaScript
正在创建我的第一个Wordpress插件,但JavaScript加载有问题 我正在定义一个类,它通过Wordpress插件:页面前加载JavaScript,javascript,php,wordpress,Javascript,Php,Wordpress,正在创建我的第一个Wordpress插件,但JavaScript加载有问题 我正在定义一个类,它通过wp\u enqueue\u script运行多个包含JavaScript的函数 下面是一个示例JS文件,演示问题: //The alert will fire alert('javascript is firing'); // This will return an error saying //Cannot read property 'setAttribute' of undefined
wp\u enqueue\u script
运行多个包含JavaScript的函数
下面是一个示例JS
文件,演示问题:
//The alert will fire
alert('javascript is firing');
// This will return an error saying
//Cannot read property 'setAttribute' of undefined
document.getElementsByTagName("body")[0].setAttribute("ng-app", "app");
plugin.php:
<?php
/*
Plugin Name: Wordpress Plugin
Plugin URI: http://www.wordpressplugin.io
Description: A Wordpress Plugin
Author: Me
Version: 1.0
Author URI: http://www.me.com
*/
define('Wordpress Plugin', '1');
class wordpressPlugin {
function __init(){
add_action( 'wp_enqueue_scripts', array( $this, 'angularScripts'));
}
function angularScripts(){
wp_enqueue_script('app', plugin_dir_url( __FILE__).'js/app.js',array('jquery'), null, false);
}
//Create instance of class
$wpNG = new wordpressPlugin();
// Activate Plugin
add_action( 'init', array( $wpNG, '__init' ), 1000 );
?>
alert('hello');
document.getElementsByTagName("body")[0].setAttribute("ng-app", "app");
警报将触发,但document.getElements
将不会运行并返回未定义的错误。但是,如果我将其包装在窗口.onload
函数中,document.getElements
将正常运行。执行窗口。onload
是不可取的
JavaScript
需要如何设置才能在不需要window.onload的情况下运行?使用window.onload是正确的方法。你为什么说它不受欢迎?我将不得不加载AngularJS和其他资源。注意到脚本没有正确运行。替换add_action('init',array($wpNG,'u_init'),1000)代码>带有add_动作('wp_head',数组($wpNG','uu init'),1000)代码>然后检查并让我知道。像这样尝试。还有一件事,如果你回复了我,那么标记我,这样我就可以得到你的回复。@KaushaMehta我是否需要使用类似add\u filter()
的东西来钩住JS函数?如果文件存在,则感觉它没有正确启动。使用window.onload是正确的方法。你为什么说它不受欢迎?我将不得不加载AngularJS和其他资源。注意到脚本没有正确运行。替换add_action('init',array($wpNG,'u_init'),1000)代码>带有add_动作('wp_head',数组($wpNG','uu init'),1000)代码>然后检查并让我知道。像这样尝试。还有一件事,如果你回复了我,那么标记我,这样我就可以得到你的回复。@KaushaMehta我是否需要使用类似add\u filter()
的东西来钩住JS函数?如果文件存在,则会感觉无法正确启动。