Creating my first Wordpress Plugin and having an issue with JavaScript loading.
I'm defining a Class which runs several functions that include JavaScript via wp_enqueue_script
.
Here is a sample JS
file Demonstrating Problem:
//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 );
?>
app.js
alert('hello');
document.getElementsByTagName("body")[0].setAttribute("ng-app", "app");
The alert will fire but the document.getElements
will not run and return an error of undefined. But, if I wrap this within a window.onload
function the document.getElements
will run fine. Doing a window.onload
is not the desirable.
How does the JavaScript
need to be set up to run without needing window.onload
?