Reputation: 671
I'm trying to run a simple JQuery script in Chrome Developer Console but I have a problem.
There is no problem in this code when I run it on Chrome Developer Console:
var someValue = $("[name='Jack']");
if(someValue !== null){
console.log("Jack is here!");
}
But, I'm getting an error when try to run the same code inside a setTimeout
function like below:
setTimeout(function(){
var someValue = $("[name='Jack']");
if(someValue !== null){
console.log("Jack is here!");
}
}, 1000);
Uncaught ReferenceError: $ is not defined
Not only does this happen in setTimeout function, it happens in a normal function as well.
I'm working with latest version of Google Chrome. How can I use JQuery like above in a setTimeout
function?
Upvotes: 3
Views: 5441
Reputation: 115910
The confusion here is centered on the fact that $
is part of Chrome's Command Line API. When you use $
in your code, you're referring to the Command Line API function named $
. You are probably not loading jQuery at all: indeed, your someValue !== null
code wouldn't even work with jQuery anyway. You'd need to test for a non-empty jQuery object (someValue.length > 0
), not a non-null
.
As for why Chrome's $
is accessible in the console but not a setTimeout
callback: this appears to be engine-specific magic that limits the command line API to console code only. setTimeout
executes its callback in such a way that Chrome cannot be sure the code originated from the console, so it does not grant access to the command line API function named $
. Curiously, this isn't typical of JavaScript. Using normal JavaScript scoping rules, the setTimeout
callback should have access to the same variables as the surrounding code, regardless of when and where it's executed. The fact that the scope is different one second later is very surprising -- you are right to feel confused!
As a curiosity, a way to simulate this in vanilla JavaScript would be with an object-based scope via with
that mutates after the command completes. For example, if every snippet you typed into the console were wrapped with:
var chromeConsoleAPI = { $: function() { ... } }
with(chromeConsoleAPI) {
// your snippet here
}
delete chromeConsoleAPI.$;
In this case, $
is supplied by accessing the chromeConsoleAPI
object on the scope chain. Normal code can access $
, but since the setTimeout
function runs after chromeConsoleAPI.$
is deleted, it does not find anything named $
. Note that this still doesn't completely replicate the behavior, because this blocks access to any user-defined $
. In actuality, the command line API must inject its functions at the very top (i.e., most remote) part of the scope chain.
Upvotes: 7
Reputation: 61
The problem because Jquery library Load after your custome code loaded.
Are you using external js file for your custome script? Then you load your script under the jquery script.
You must add jquery library link first then add your script.
Upvotes: 0