Why isn't my javascript loading in my WordPress plugin? - javascript

I'm working on a plugin that uses jquery (already loaded in the head). I can't get my plugin's javascript to load:
function add_my_js(){
echo 'joy joy joy';
wp_register_script('hdjs',plugins_url('/css/homedepotslider.js', __FILE__));
wp_enqueue_script('hdjs');
}
add_action('wp_print_scripts','add_my_js');
It will run the function (I see the "joy joy joy") but not load the script. Note: the "joy" text was being used to see if the function even runs.
I loaded my plugin css the same way (using _style) and have no issues.
Thanks!

You are looking in the wrong directory; I doubt the js file is in the css directory.
Always be careful when copy and pasting.
I imagine it should look like:
function add_my_js(){
echo 'joy joy joy';
wp_register_script('hdjs',plugins_url('/js/homedepotslider.js', __FILE__));
wp_enqueue_script('hdjs');
}
add_action('wp_print_scripts','add_my_js');

Related

Find and remove remaining assets for plugin in wordpress

I'm trying to optimize some wordpress sites for speed etc...I have one site where remnants of a plugin are still around..It's called five9 chat and it's showing up when I do a performance test but I can't seem to find where it's coming from in the source files.
…SocialWidget/five9-social-widget.min.js(app.five9.com)
Any idea on where to find this and remove it from running on my site?
check the page source code and check the id of that script.
example :- <script src='//cdn.jsdelivr.net/npm/select2#4.1.0-rc.0/dist/js/select2.min.js?ver=1.0.0' id='select2js-js'></script>
then id should be 'select2js'.
then add the following code in your theme function.php file to dequeue that script.
Note :- replace script id.
<?php
function wpdocs_dequeue_script() {
wp_dequeue_script( 'select2js' );
}
add_action( 'wp_print_scripts', 'wpdocs_dequeue_script', 100 );

"TypeError: $ is not a function" after loading some scripts into wordpress

We start to provide a HTML-Snippet like Google or Facebook does for its advertising things or the integration for the Facebook like button. It contains a business application.
Our HTML-Snippet loads a script and contains a few more informations:
<div id="ncc" data-hash="" ng-jq>
<div id="wiz" ng-controller="WizardCtrl"></div>
<script src="{{URLTOSCRIPT}}/load.js"></script>
</div>
The script checks if a jQuery is installed and loads all related things into the DOM and at the ends inits an angular-Application.
All this works fine on pages that havn't enabled jQuery.noConflicts-Mode.
After the latest Wordpress-Updates we got an ERROR
"TypeError: $ is not a function"
We tried to get rid of it using some workaroungs like
jQuery(document).ready(function($){
$(function () {
//code to execute
});
OR
jQuery(document).ready(function(){
var j = jQuery.noConflicts();
j(function () {
//code to execute
});
and changed also all references in the angular-part. But nothing working really well.
Any suggestions?
We are using AngularJs v1.4.7, jQuery v1.11.3 (started to migrate to 2.1.4), the
Sometimes when more versions of jQuery are loaded or if it conflicts with another library you can get that error:
have you tried to replace in all of your code the $ symbol with the word "jQuery"?
So your example would become:
jQuery(document).ready(function(){
jQuery(function () {
//code to execute
});
Note: I don't think that in this case passing "$" as a parameter is needed anymore ;)
EDIT: there is also another possibility:
you say that you're using the $ sign (i guess to avoid the usual conflicts in wordpress) in this way:
jQuery(document).ready(function($){
$(function () {
//code to execute
});
But this will make the $ symbol available only inside the ready() function.
Did you check if you have somewhere code using the $ where you actually aren't allowed to (or in other words if you have any piece of your js code where $ isn't mapped as "jQuery")?
EDIT 2: The only working solution in the end was:
(function($,undefined){
$(document).ready(function(){
//code to execute
});
})(jQuery);"
Make sure jQuery is loaded before any other script that uses certain jQuery functions.
Normally those errors arise, when the jQuery library wasn't loaded yet. Make sure that a $()-call is called after jquery was loaded, which normally happens at the end of your file to speed up loading times.
Therefore putting
<script src="{{URLTOSCRIPT}}/load.js"></script>
to the end of the body-tag should help.
Usually when you get this error: "TypeError: $ is not a function"
it means, you a missing a JQuery library or they are not placed in the correct order. Ordering JQuery libraries is important.
$ is not a function. It means that there is a function named $, but it does not have a plugin/widget named selectable. So, something has stolen your $ or there is another library added after it, or it was never loaded.
Your script file is not loading properly or script file is not available.
open browser inspect element and put this code
jQuery().jquery.
it's display which jquery version is use.
this is for testing
jQuery(document).ready(function()
{
alert("test");
});

how do I include an external javascript file with bootstrap

I'm trying to figure out how to include an external javascript file while I am using the bootstrap framework. I figure it should be very simple to do but it seems to be giving me fits.
I have scripts/dsc.js that I am trying to load into a <div id="loadedContent"></div>
The line of code in the JSP file is:
<li>View Job (All Runs)</li>
in the external javascript file I have this as my simple javascript:
$(function() {
alert("Hi");
loadlLocation = function(location) {
$("#includedContent").load(location);
};
});
I put this in the head declaration:
<script src="scripts/dsc.js" type="text/javascript"></script>
I know that the src path is correct because the other includes for the bootstrap scripts work just fine. The alert located in the dsc.js is not showing up with is pointing me to it not being included. Now, Bootstrap by default was loaded at the bottom (so I left it there), but I included my javascript file in the head declaration. Is there something special that I have to do to include javascript files when using Bootstrap?
That cant work! You have no access outside the jQuery Wrapper!
var loadlLocation = function(location) {
$(function() {
$("#includedContent").load(location);
});
};
It actually ended up being an ordering problem. Was already solved here by KirKill.
How do i add jquery ui date picker, while already working with bootstrap library?

managing common jquery script files in asp.net project

I'm looking for best practices for using javascript/jQuery snippets in an asp.net project. I know that it is best to put all the scripts in a separate file rather than inline. That's good. It is easy to move these script functions to a common file (may be a couple of different ones to even out the performance of loading a single large file for small functions).
But there is some jQuery stuff that needs to happen on document.Ready on each page. How will I move this to a common .js file? I would like to avoid one script per page as it would be just too many.
For example, say Page1 has a need to manipulate a few radio buttons on load and has the following script inline. (just for illustration)
<script>
$(document).ready(function() {
//check checkboxes
if(true)
call function1();
});
</script>
Same with Page2 but for some other condition, calling different function function2.
I can move the function1 and function2 to a common .js file but how about the document ready sections. Should that stay inline? I assume so because otherwise I'm not sure how the common.js will differentiate between document.ready for different pages.
Then does it defeat the purpose of not having inline javascript? If anyone can throw some light into this, it is much appreciated.
I did some research, but probably due to incorrect keywords, so far I haven't been able to find any good information along the same lines. Unobtrusive JavaScript seems promising in the comments below.
You should specify what behaviors should exist within the HTML using data-* attributes.
You can then use a single universal piece of Javascript code to read these attributes and apply behaviors.
For example:
<div data-fancy-trick="trick-3">...</div>
In the JS file, you can write something like
$('[data-fancy-trick]'.each(function() {
var trickName = $(this).data('fancy-trick');
switch (trickName) {
...
}
});
For real-life examples of this technique, look at Bootstrap's Javascript components.
You can simply have separate js files per page and include them in relevant pages. For shared script code, have a common js file. Following your example:
common.js
var myCommonVar = {};
function myCommonFunction(...){
...
}
page1.js
$(document).ready(function() {
...
function1();
...
});
page2.js
$(document).ready(function() {
...
function2();
...
});
page1.html
...
<script src='/js/common/js'></script>
<script src='/js/page1.js'></script>
...
page2.html
...
<script src='/js/common/js'></script>
<script src='/js/page2.js'></script>
...
Consider the usage of AMD (Asynchronous Module Definiton) design pattern. Put your JavaScript code into modules and on each page use just those you really need to. For example requirejs does a great job and I've been using it with success. If you have a bigger project you can split your modules into namespaces. This approach will keep excellent code maintainability and it's reliable. You simply put the "starter" javascript file on each page and load only those required modules you need to work with per each page.
There are many ways to deal with this problem, either using a JavaScript Framework that is aiming to treat your website as a 'Webapp' (Angular and Ember among the popular), or using your own custom script that will do just that - invoking the appropriate JavaScript per loaded page.
Basically, a custom script that will be able to handle it, will have to make use of (pseudo) 'Namespaces' to separate modules/pages code sections.
Assuming you have 2 hypothetical pages, Home and Browse, Simplified code sample may look like this:
HTML:
<body data-page="Home">
Global.js:
var MyApp = {}; // global namespace
$(document).ready(function()
{
var pageName = $('body').data('page');
if (pageName && MyApp[pageName] && MyApp[pageName].Ready)
MyApp[pageName].Ready();
});
Home.js:
MyApp.Home = MyApp.Home || {}; // 'Home' namespace
MyApp.Home.Ready = function()
{
// here comes your 'Home' document.ready()
};
Browse.js:
MyApp.Browse = MyApp.Browse || {}; // 'Browse' namespace
MyApp.Browse.Ready = function()
{
// here comes your 'Browse' document.ready()
};
MyApp.Browse.AnotherUtilFunc = function()
{
// you could have the rest of your page-specific functions as well
}
Also, since you're using ASP.NET MVC, sometimes your Controller name may fit as the qualified page name, you can set it automatically in your Layout.cshtml (if you have one):
<html>
<head>
</head>
<body data-page="#ViewContext.RouteData.Values["Controller"].ToString()">
#RenderBody()
</body>
</html>
I think its not worth stuffing up everything in a single file and separating them with conditional statements, just to avoid adding a reference on the respective file.
If you have code that can be called on 2,3 or more pages, then we can opt for having them in a common file. But if its going to be called on a single page then we must write code on the respective page only. This will also increase the overhead of declaring the functions that are not going to be called on the current page
And when you are using the common js file, then you don't need to worry about the $(document).ready(); event, you can use a single ready event in the common file and separate the code by using conditional statements.
The new versions of the script manager will combine everything into one blob of a script. In theory it makes fewer round trips and things run faster. In practice you could end up with several large scripts that are nearly identical and each page needs its own blob of a script. If your making one of those never change the url website pages then this is the way to go.
I came up with these best practices when I was working with jquery on ASP.Net
Load Jquery in your master page above the first script manager. Jquery is now available on every page. The browser will only get it once and cache it.
If bandwidth is an issue use a jquery loader like googleload or MS content delivery network
Document.load is always at the bottom of the page to guarantee that everything needed is already loaded.
From my blog that I haven't updated in years...Google Load with ASP.Net
One common way to address this problem would be to have your common script include followed by a per-page script element:
<!-- In 'shoppingcart.html' -->
<script src="main.js"></script>
<script>
// Let there be a onDomReady JS object inside main.js
// that defines the document.ready logic on a per-page basis
$(document).ready(onDomReady.shoppingCart);
</script>
Great question, I have been dealing with the same thing.
Here is what I have been doing:
Have your $(document).ready() call different init functions (if they exist), where each .js file has its own init which adds event listeners and loads functions, messes with css, etc.. Each .js file is separated out into different pieces of functionality.
This way you have one document ready that calls all of your initializers. So each page would include the .js functionality it needs. This way you can separate out what is different.
ex:
ready.js:
$(document).ready(function(){
if (typeof menuNavInit == 'function'){
menuNavInit();
}
if (typeof menuNavDifferentInit == 'function'){
menuNavDifferentInit();
}
//other .js functionality
});
menuNav.js
function menuNavInit(){
$("#menu").on('click', menuNavClick)
}
function menuNavClick(){
//do something
}
menuNavDifferent.js
function menuNavDifferentInit(){
$("#menu").on('click', menuNavDifferentClick)
}
function menuNavDifferentClick(){
//do something else
}
page1.html
...
<script src='scripts/ready.js'></script>
<script src='scripts/menuNav.js'></script>
...
page2.html
...
<script src='scripts/ready.js'></script>
<script src='scripts/menuNavDifferent.js'></script>
...

jQuery .load() function (not loading files completely)

I've been struggling with query for some time. I have a CMS that I want to use on my site, but I cant use PHP includes so I decided to use jquery. I have made all the necessary includes and when I open the webpage it doesn't load all the files... Rarely does load() function load every file. Any ideas to solve the problem or alternatives? thanks.
<script type="text/javascript">
$(document).ready(function () {
// find element with ID of "target" and put file contents into it
$('#welcome-container').load('admin/data/blocks/Slider/Text.html');
$('#slides').load('admin/data/blocks/Slider/Imagini.html');
$('#acasa-continut').load('admin/data/blocks/Acasa/Continut.html');
$('#sidebar').load('admin/data/blocks/Sidebar/Continut.html');
$('#sidebar-v1').load('admin/data/blocks/Sidebar/Video-1.html');
$('#sidebar-v2').load('admin/data/blocks/Sidebar/Video-2.html');
$('#principii').load('admin/data/blocks/Despre/Principii.html');
$('#echipa').load('admin/data/blocks/Despre/Echipa.html');
$('#echipament').load('admin/data/blocks/Despre/Echipament.html');
$('#contact-t').load('admin/data/blocks/Contact/Contact.html');
});
</script>

Categories