I'm using requireJS and am trying to define a Google maps module.
I'm adding this code to the end of HTML snippet:
$(document).ready(function() {
console.log("ready");
define(['async!http://maps.google.com/maps/api/js?v=3&sensor=false'],
function (gmap) {
console.log(gmap);
});
});
The "ready" console is logging but the define call is not triggering. If I replace it with a require call, the file is being loaded, but I gmap is undefined.
Question:
why is my define call not triggering?
It's because once a module is defined it needs to be required. Changing your code to something like this would work:
// gmap.js (for example)
define(['async!http://maps.google.com/maps/api/js?v=3&sensor=false'], function(gmap) {
// Do some stuff
return gmap;
});
// main.js
require(['jquery', 'path/to/gmap'], function($, gmap) {
$(function() {
console.log(gmap);
});
});
Some things to note:
Modules that are defined should live in individual files. Read this page in the API documentation to grasp how they work.
Avoid requiring modules inside a DOM ready callback, this means you have to wait longer before the modules can be requested. Better to start requesting them straight away and check for DOM readiness later. RequireJS comes with a DOM ready plugin just for this.
Ensure you require jQuery as a module (unless you aren't using it as such).
Passing an anonymous function to $() is a shortcut for $(document).ready()
Related
I'm getting a $ not defined error in the second case below, but not the first. jQuery is installed and working on the site.
Any code using $ in here runs fine:
jQuery(function($) {
alert("Yay!");
});
Anything inside of this errors with $ not a function:
jQuery(window).load(function($) {
alert("Why not!");
});
The error is because the load() event handler does not accept a jQuery object as an argument as document.ready (which is what your first example is shorthand for) does. In the second example your $ variable is actually a reference to the Event object, as such you're probably calling methods which don't exist.
If you want to use $ to reference jQuery, then it should be available by default. If for whatever reason it isn't, for example if you're using Wordpress, then you can use jQuery.noConflict() or an IIFE to re-alias it.
It's also worth noting that load() is deprecated. To hook to the window.load event use on():
jQuery(window).on('load', function() {
// your logic here...
});
I have multiple scripts tags loading to the DOM. But I would instead like to wrap all of them like so:
$(document).ready( () => {
// load script1.js
// load script2.js
// load script3.js
// etc.
});
This way I could avoid funky scoping issues if each individually loaded file had a $(document).ready() function.
I am trying to use functions defined in the previous script tags within $(document).ready( // use functions in here) without crowding the global namespace.
If more information is needed, I will be happy to provide it. Thanks.
The $(document).ready() is a global function. It is called only once if the complete DOM is ready. This includes all script tags. So you can do all that things in one function.
See the jquery docs too. http://learn.jquery.com/using-jquery-core/document-ready/
For example:
$(document).ready (function () {
// Init of script1.js
// Init of script2.js
})
I hope this helps.
I'm having some issues with running some functions from an external js file.
The html includes:
<script src="js/file.js"></script>
<script>
$("#center-button").click(function() {
explodePage("center");
});
</script>
The js file includes:
var explodePage = function(button) {
//code here
aboutPage();
}
var aboutPage = function() {
//code here
}
The explodePage function runs fine, but as soon as it reaches the call to the nested aboutPage function, it starts throwing these uncaught typeerrors at me. It works fine if I don't use an external js file and just put everything into the html. Pretty new to this so probably missing something obvious in scope or something. Any solutions?
Declare the function's definition as below:
function explodePage(button) {
//code here
aboutPage();
}
function aboutPage() {
//code here
}
Explanation:
When you use the var keyword for declaring functions, the execution of JS happens as when the variable is initialized, you cannot reference or use variable's before declaration. In contrast with the name function defintion JS interpreter first picks the enclosed functions before execution and initializes it before the code execution. This is called AST- Abstract syntax tree that is followed by JS interpreters.
Also Remember:
Also bind your Jquery code inside a Jquery document ready function, just to make sure the Jquery and the DOM elements are available for the bindings.
It's not a good a idea to pollute the global window object with variables, since there can be collisions. And immediately-invoked function expression is a good solution for this.
(function(){
//You can declare your functions in here, and invoke them below
$( document ).ready(function() {
//Check that the DOM is ready, in order to manipulate it an add events
$("#center-button").click(function() {
explodePage("center");
});
});
})($); //Notice that we are injecting a dependency, in this case jQuery
What I need is pretty simple, although I don't know if possible..
I'm attaching all my event handlers to the object themselves instead of to $(document).
But, I need to attach them on the .ready() method, to make sure the object is created before the handler is attached. Since there are a lot of handlers to attach, to keep my code cleaner I want to create a function called attachHandlers() that will be called on document.ready().
But.. this function should execute codes that are in multiple files.
My question is.. is there a way of declaring the same function multiple times, and then calling it just once to execute them all?
But.. this function should execute codes that are in multiple files.
My question is.. is there a way of declaring the same function
multiple times, and then calling it just once to execute them all?
If interpret Question correctly, you want to request javascript from multiple files at .ready() . You can create an array containing url of file to request, use $.when(), $.map(), $.getScript() to call the javascript within the files
jQuery.getScript( url [, success ] ) Returns: jqXHR
Description:
Load a JavaScript file from the server using a GET HTTP request, then
execute it.
The script is executed in the global context, so it can refer to other
variables and use jQuery functions. Included scripts can have some
impact on the current page.
$(document).ready(function() {
var files = ["1.js", "2.js", "3.js"];
$.when.apply($, $.map(files, function(file) {
// request file
return $.getScript(file)
}))
.then(function() {
// complete
// do stuff
}, function err(jqxhr, textStatus, errorThrown) {
// handle error
});
});
Create a global JS file that has this function (and future functions that you want to be run on all pages). Call this script at the top of each file in the head element. Calling it in the head should do what you need (at least that is what i use in my projects and works for me).
Can u package your multiple files in modules and every one of them has a method attachHandlers? Then try use requirejs to load all of them. In document.ready, call the attachHandlers method from all these modules? It will be neater
jQuery(document).ready(function($){}); is a known and great way to protect the $ from causing errors.
What I'm curious about is if jQuery(window).load(function($){}); would work in the same way?
Basically, what I have now is:
jQuery(document).ready(function($){
$(window).load(function(){
// ...
});
});
This just seems unnecessary to me, any ideas about simplifying this? I need the safety of having jQuery properly mapped to $ (or whatever the correct term is) but the same timing as window.load()
I prefer this...
(function($){
$(window).load(function(){
//everything is loaded (images, scripts, etc.)
});
// and/or
$(document).ready(function(){
// the dom is in place, but everything is not necessarily loaded
});
})(jQuery);
Note: This will only work if jQuery was included before this script. I have never encountered any problems with jQuery being undefined this way. Furthermore, you will never have problems with $ being undefined, because you are passing it into your anonymous function.
You can do this:
(function($) {
$(window).load(function(){
// ...
});
})(jQuery);
The anonymous function will be executed immediately rather than waiting for DOM ready as in the code in the question. Within the function $ will be a reference to jQuery so won't clash with any other $ defined outside the anonymous function.
You can create a local parameter:
(function($) {
$(...)
})(jQuery);
This code executes an anonymous function with a parameter named $, passing jQuery as the parameter value.