Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/258.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Wordpress插件:页面前加载JavaScript_Javascript_Php_Wordpress - Fatal编程技术网

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

正在创建我的第一个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
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函数?如果文件存在,则会感觉无法正确启动。