ERROR: Execution of script failed! $ is not defined - javascript

I've used my script on Tampermonkey (Firefox) for 6 month.
At now I have this error, script work partially, not all time.
I don't know why.
I have tries various suggestions about jQuery, doesn't work
Top of my script:
(function() {
'use strict';
function RPP(){
RedeemRPProduct('fp_bonus_100');
}
var body = $('body'); //I think error is here..
var points = {};
At now script works some times. When it doesn't works appear in console this error:
ERROR: Execution of script 'script-name' failed! $ is not defined
What's happened?
Thanks

I think the cause is that the website administrators removed jQuery from their code. With modern JS, it's mostly obsolete for things like selectors. I recommend simply removing jQuery references from your script and use normal DOM API:
To access body:
document.body
To find an element using selector:
document.querySelector("div#my_div")
Alternatively you could include jQuery in your script using #require.

I see your problem is solved, but leaving this here for others with the same error...
I'm also using Firefox, and my Tampermonkey was 1 year old (I forgot that I disabled the addon's auto updating). It worked fine, I never had the problem you described. Till a couple of days ago when I updated to the new version, and my userscripts stopped loading 10% of the times (got the mentioned error message in console).
Newer Tampermonkey-s are much faster than older versions, loading the userscripts earlier, sometimes before the jQuery library script of the original site is loaded, even if you are using // #run-at document-end.
How I fixed: wrapped my whole userscript content into 1 function, which is called only when the jQuery script is 100% loaded, using a checker function.
Add the next line to the top of your script, right after the Header:
function runScript() {
Add the next lines to the bottom of your script (to the end):
};
var waitForJQuery = setInterval(function () {
if (typeof $ != 'undefined') {
$(runScript);
clearInterval(waitForJQuery);
}
}, 100);

You're referencing jQuery (via the $) before it has loaded into the page.
It is working sometimes as I'm guessing on some occasions jQuery manages to load before you make your call...but sometimes it doesn't and you see the error.
Try this:
<script src="...your jquery reference..."/> <!-- at the top of your page -->
<!-- at the bottom of the page -->
<script>
var body;
var points = {};
document.addEventListener("DOMContentLoaded", function() {
body = $(body); //it won't try and use jQuery until the doc is ready
//...other script stuff...
});
</script>

Related

IE8 seems to execute js before css is rendered

I've got a weird problem. I'm using Bootstrap for a website that has to be optimized for IE8. When i test the html prototype in a real IE8 (no IE emulation) the javascript seems to be executed before the website is rendered.
To prevent this I placed the javascript at the bottom of the body and the script is surrounded by a window load function.
Do i miss something? I don't want to use a SetTimeout.
A short js code example.
$(window).load(function() {
// for example a function that resets the sliders offset
function reset_slider() {
$('.slider-main').css({'margin-top': '0px'});
}
reset_slider();
}
All Browsers beside IE8 execute this script after the site is rendered.
Thanks in advance
Marcus
Set your js function to load after the page has.
window.onload = yourfunction
or you could use:
<body onload="yourfunction();">

jQuery No Conflict Wrapper Not Working

I'm getting the dreaded Uncaught TypeError: undefined is not a function error in WordPress. I'm pretty sure that I've properly enqueued my jQuery script (it's showing up properly in the footer), and I've used the following no conflict wrapper at the start of my code: jQuery(document).ready(function($) {.
I've tried replacing all $ variables with jQuery. I've also defined var $j = jQuery; and replaced all $ variables with $j.
There are other theme-generated jQuery scripts on the page that are working (embedded, not enqueued), so there might be potential conflicts, but I'm not sure how to debug that.
Any help appreciated. I can provide link to the site if that helps.
EDIT
I had this script working perfectly earlier from within the jQuery UI Widgets plugin, but that plugin seemed to be causing serious issues (crashed my site). So I disabled the plugin, and I haven't been able to get the script working since.
That doesn't look quite right. Try this
(function($) {
$(document).ready(function() {
console.log("dom is ready");
});
})(jQuery);
You could try this:
var j = jQuery.noConflict();
j(document).ready(function () {
...
//replacing all Dollar Signs with the j
});
That's what worked for me

Prevent inline scripts loading until Jquery has been loaded

Ok, I have a Jquery script, its function is to determine the width of the window, onload. If the width is greater than 642px it calls .load() to load an image slider. The reason for this is mobile devices will neither be served the images or js required for the slider.
This worked fine when jquery was loaded in the head. Upon moving to the footer its breaking. The code is included from the index.php. Could this be whats causing it? I would have thought once php built the page jquery parsed the content?
It appears the code is parsed before the jquery is loaded. Can anyone suggest a way to get round this please?
I have thought of creating the code as pure JS or using a delayed load, but I cant seem to figure out how to get it working.
There must be much better solutions? I feel like I’m missing something very obvious..
contents of the included script:
<script type="text/javascript">
$(window).bind("load", function() {
// code here
$(window).width(); // returns width of browser viewport
var width = $(window).width();
if (width >= 642) {
$('.slider-content').load("templates/include/slider.php", function () {
$('.slider-content').show(200);
});
}
else {
//alert('small')
}
});
</script>
Thanks,
Adam
In some environments, you must use jQuery() instead of $(). See this question.
Other than that, your problem might have to do with the document not being complete yet or binding to an event that has already passed. Try this instead:
jQuery(document).ready( function($) {
// Your code goes here. (You can safely use the $() function inside here.)
});

Using jQuery noConflict() with script.aculo.us

I have a site using a "widget" (from http://healcode.com) that includes the script.aculo.us JavaScript library. The problem is that the site I'm building is on WordPress, so there's the classic jQuery vs script.aculo.us conflict.
I know that I need to run jQuery in .noConflict() mode, but I must be getting the syntax wrong. When I assign the $ to jQuery .noConflict as follows, it still shuts down the script.aculo.us functions:
var $ = jQuery.noConflict();
$(document).ready(function () {
//#nav-main dropdown effects
$('#nav-main ul li').hoverIntent(function () {
$(this).find('.dropdown').stop(true,true).slideDown('900'); },
function(){
$(this).find('.dropdown').stop(true,true).slideUp('500');
});
}); // end document.ready
I know that I am assigning the $ to jQuery in .noConflict() mode, and I assume that script.aculo.us (which loads via a widget in the main body, therefore AFTER jQuery) is trying to re-assign the $ back to script.aculo.us.
How can I assign the $ to jQuery in a way that the later-loaded script.aculo.us library won't conflict? I've already tried the following without any success (the following code causes script.aculo.us to work, but jQuery to fail):
jQuery(document).ready(function () {
//#nav-main dropdown effects
jQuery('#nav-main ul li').hoverIntent(function () {
jQuery(this).find('.dropdown').stop(true,true).slideDown('900'); },
function(){
jQuery(this).find('.dropdown').stop(true,true).slideUp('500');
});
}); // end document.ready
EDIT
The debug console output for the above code is:
Uncaught TypeError: Object #<HTMLDocument> has no method 'ready' (anonymous function) so the document.ready fails because it's assigned to jQuery, which is somehow not loading properly...
EDIT 2
Both of the 2 (at the time of this update) answers posted below do nothing to address the issue I'm struggling with. Perhaps they are technically correct, but they do not address my issue.
This worked for me so that I can have jQuery and script.aculo.us/Prototype working well together. Credit goes to codeimpossible for this lifesaver!
Instead of:
jQuery(document).ready(function () {
// Code to run on DOM ready
}); // End document.ready
Try this:
( function($) {
// Code to run on DOM ready
} )( jQuery ); // End document.ready
I found the solution VERY surprising!
First of all, using the $j = jQuery.noConflict(); mode did not work.
Second, calling jQuery.noConflict(); at the head did not work.
The method that did work was this one: http://codeimpossible.com/2010/01/13/solving-document-ready-is-not-a-function-and-other-problems/
Oddly, the Coda Slider 2.0 plugin does not automatically do noConflict so it turned out that IN ADDITION to the problems listed above, I needed to wrap that plugin in .noConflict(); as well. Shout out the the author of the blog post, not sure why other noConflict(); calling methods didn't work, but I'm glad I found the post.
Assigning jQuery right back to $ doesn't do anything.
Either assign jQuery to a different variable:
var j$ = jQuery.noConflict();
Or don't assign it to anything:
jQuery.noConflict();
Try this:
<script src="url to jquery"></script>
<script type="javascript">jQuery.noConflict();</script>
<script src="url to scriptaculous"></script>

jQuery inside Media Wiki pages (not just in the Monobook.js or extensions)

I'm trying to do some simple jQuery stuff 'dynamically' from within a MediaWiki content page. Its really just to 'beauty up' some different features.
I've done the following:
http://www.mediawiki.org/wiki/JQuery
http://www.mediawiki.org/wiki/Manual:$wgRawHtml (mainly for Paypal buttons initially)
The below code does not work. This is put in a blank content page.
<html>
<script>
$j(document).ready(function(){
$j('#test').hover(
function(){
$j('#test').attr('background-color','red');
},
function(){
$j('#test').removeAttr('background-color');
}
);
});
</script>
<div id="test">Howdy</div>
</html>
Nothing happens...
Any ideas?
Update:
I have attempted this simple solution with no result.
example.com/wiki/index.php?title=MediaWiki:Common.js
$j('#jTest-Howdy').hover(
function(){
$j('#jTest-Howdy').addClass('jTest-red');
},
function(){
$j('#jTest-Howdy').removeClass('jTest-red');
}
);
example.com/wiki/index.php?title=MediaWiki:Common.css
.jTest-red { background-color: red; }
example.com/wiki/index.php?title=jQueryTest
<html>
<div id="jTest-Howdy">Howdy</div>
</html>
as you can see here, this code should work IF jQuery was being loaded properly...
http://jsfiddle.net/5qFhv/
but it is not working for me... any help?
If you're using the jQuery that's loaded by MediaWiki 1.17, be aware that most JavaScript is loaded after page content. An inline <script> element is executed immediately when it's reached, so $j would not be defined at this time -- you'll probably see some errors in your JavaScript error console to this effect.
(Offhand I'm not sure about the jQuery that's included with 1.16; versions of MediaWiki prior to that as far as I know did not include jQuery.)
Generally what you want to do here is to either put JavaScript code modules into the 'MediaWiki:Common.js' page and let that hook up to your HTML markup, or create a MediaWiki extension -- which you can then invoke from your pages, and which will let you create any fun HTML and JavaScript output you like.
http://www.mediawiki.org/wiki/Manual:Interface/JavaScript
http://www.mediawiki.org/wiki/Manual:Developing_extensions
Code you put in your 'MediaWiki:Common.js' page will be loaded after other UI initialization, ensuring that code and variables are present so you can call into jQuery etc.
I don't know much about MediaWiki, but to me it looks like some simple javascript mistakes.
In the first sample you are trying to set an attribute on the element,
when you need to set the css or style attribute.
$j('#test').css('background-color', 'red');
In both samples you are binding an event to an element that doesn't exist yet in the DOM, so it will fail. You could use the live method, which will work for existing and future elements introduced in the DOM.
$j.('#test').live('mouseover', function(){
$j(this).addClass('hover-class');
}).live('mouseout', function(){
$j(this).removeClass('hover-class');
});
Hope that helps.
Try putting all your custom jQuery code in its own file, then load it as a module with ResourceLoader, after jQuery.
http://www.mediawiki.org/wiki/ResourceLoader/Migration_guide_for_extension_developers
Also, as a debugging method: completely load your site in Firefox, then enter your custom jQuery code in the console. If it works, your problem is a race condition. If it doesn't, jQuery isn't loading for some reason.

Categories

Resources