Jquery Call Default Load Function Jquery Call Document Ready Again
By Burke Holland
When I first started using jQuery, I was so excited. I was using vanilla JS and actually struggling with agreement when elements on a page were ready and how I could admission them. When I learned about jQuery, I think I did what many people do. With tears of joy running down my confront, I opened upwardly a document gear up part and and so just vomited up massive amounts of jQuery.
Some of the worst jQuery code ever written was written by me – I tin clinch you of that.
Since then, I've spent a few years at the Bayside of jQuery. I've had my centre broken a few times and learned a some things along the way. In doing so, I'd like to share 5 things in jQuery that I call up you should think twice about doing.
1. Stop Using Document Set up
Back in the day of heavy server frameworks, knowing that your page was fully synthetic before yous tried to mutate it was a big deal. This was specially true if you were using partial views of some sort that were injected into the layout/master folio past the server at runtime.
Present, it'south considered best practice to include your scripts at the bottom of the page. The HTML5 async attribute notwithstanding, scripts are loaded and executed synchronously by the browser. That ways that if you accept a big script in the caput of your page, information technology will delay loading of the DOM and make your page seem slower than it actually is. Loading all scripts last will at least make your application seem to load faster. It besides gives yous a chance to utilise a spinner or loading overlay if yous are completely dependent on JavaScript for your UI.
If you lot are adhering to the "scripts at the bottom" best practice, and so you have no need for jQuery's document gear up office as the HTML is already loaded past the time the script is run.
<p id="zack">This element is on the page <strong>BEFORE</potent> all the scripts. No document ready needed.</p> <script src="https://ajax.googleapis.com/ajax/libs/jquery/ane.9.ane/jquery.min.js"></script> <script type="text/javascript" charset="utf-8"> // if you include your scripts at the very lesser, you don't need document prepare (part($) { $("#zack").css("color", "green"); $("#slator").css("color", "red"); }(jQuery)); </script> <p id="slater">This element comes after the scripts and won't be bachelor.</p>
2. Stop Using The Wrong Iterator
I've got no difficult prove to back this upward, but I'd exist willing to guess that the each role is the most used of the jQuery utility methods. I base of operations this on how often I am tempted to use it and how often I see information technology in other people's code. Information technology's incredibly user-friendly for looping over DOM elements and JavaScript collections. It's likewise terse. At that place is nothing wrong with it, except that its not the only iteration function the jQuery provides. People employ each like it's Zack Morris, at which point every looping trouble starts looking like Kelly Kapowski.
MAP
If yous have an array of items and you lot want to loop through it and filter out some of the items, you might exist tempted to employ the each method like so:
(office($) { var allStarCast = [ { firstName: "Zack", lastName: "Morris" }, { firstName: "Kelly", lastName: "Kapowski" }, { firstName: "Lisa", lastName: "Turtle" }, { firstName: "Screech", lastName: "Powers" }, { firstName: "A.C.", lastName: "Slater" }, { firstName: "Jessie", lastName: "Spano" }, { firstName: "Richard", lastName: "Belding" } ] // iterate through the cast and find zack and kelly var worldsCutestCouple = []; $.each(allStarCast, part(idx, actor) { if (thespian.firstName === "Zack" || histrion.firstName === "Kelly") { worldsCutestCouple.push(actor); } }); panel.log(worldsCutestCouple); }(jQuery));
Try It
That works, only jQuery actually provides a method specifically for this scenario and information technology's called map. What information technology does is takes whatsoever items that get returned and adds them to a new array. The looping code so looks similar this…
(office($) { var allStarCast = [ { firstName: "Zack", lastName: "Morris" }, { firstName: "Kelly", lastName: "Kapowski" }, { firstName: "Lisa", lastName: "Turtle" }, { firstName: "Screech", lastName: "Powers" }, { firstName: "A.C.", lastName: "Slater" }, { firstName: "Jessie", lastName: "Spano" }, { firstName: "Richard", lastName: "Belding" } ] // iterate through the cast and observe zack and kelly var worldsCutestCouple = $.map(allStarCast, role(actor, idx) { if (histrion.firstName === "Zack" || actor.firstName === "Kelly") { return player; } }); console.log(worldsCutestCouple); }(jQuery));
Try It
Did you lot notice that the arguments for the .map() callback and the .each() callback are reversed? Spotter out for that because information technology can bite you when yous start using map.
The map office allows you to modify the items earlier they go slapped into the new array. I'm not currently doing that, then technically I'm still not using the "correct" iterator. I should really be using grep.
GREP
If you spend most of your days on Windows, so this term might exist foreign to you lot. The term is typically used for a Unix control line utility for searching files that contain text matching a given regular expression.
In jQuery, grep is a role whose purpose is to reduce a drove by removing elements that don't pass the exam in the callback. The provided callback returns a boolean value. Return true if y'all want the item to remain, and false(y) if you don't. It will not affect the original array. You cannot change the items as y'all reduce them.
(office($) { var allStarCast = [ { firstName: "Zack", lastName: "Morris" }, { firstName: "Kelly", lastName: "Kapowski" }, { firstName: "Lisa", lastName: "Turtle" }, { firstName: "Screech", lastName: "Powers" }, { firstName: "A.C.", lastName: "Slater" }, { firstName: "Jessie", lastName: "Spano" }, { firstName: "Richard", lastName: "Belding" } ] // iterate through the cast and notice zack and kelly var worldsCutestCouple = $.grep(allStarCast, part(actor) { render (histrion.firstName === "Zack" || actor.firstName === "Kelly"); }); panel.log(worldsCutestCouple); }(jQuery));
Try It
iii. Stop Using "this"
This isn't a jQuery issue, simply jQuery can definitely exacerbate the problem. The context of "this" is always changing. jQuery sometimes changes the context to something that y'all might not be expecting. In the each callback, this is the current item or chemical element in the collection. In the map function, information technology's the window object. You can run into how y'all could become yourself confused pretty quickly.
Have a look at the post-obit example and then we'll talk about why it blows upward.
(function($) { var sbtb = { log: function(message) { $("#log").append("").html(message); }, cast: [ { firstName: "Zack", lastName: "Morris", soExcited: fake }, { firstName: "Kelly", lastName: "Kapowski", soExcited: truthful }, { firstName: "Lisa", lastName: "Turtle", soExcited: true }, { firstName: "Screech", lastName: "Powers", soExcited: false }, { firstName: "A.C.", lastName: "Slater", soExcited: fake }, { firstName: "Jessie", lastName: "Spano", soExcited: true }, { firstName: "Richard", lastName: "Belding", soExcited: false } ], soExcited: function() { // use "this" to get a reference to the cast on this object $.each(this.cast, part(idx, player) { // call the log function this.log(actor.firstName + " " + actor.lastName); // BOOM! Splosions. // "this" is now a cheesy thespian, not the sbtb object anymore }); } }; sbtb.soExcited(); }(jQuery));
I wanted to log out everyone who was "then excited". I'm in an object then I can get a reference to the object with this. Then I loop through the object and look for the "isExcited" flag. All the same, equally soon as I enter the loop callback, the context of this has inverse and I tin't access the object anymore.
Since jQuery is changing the scope for you in these loops, it's a good idea to store the reference to this somewhere so that you know information technology's not going to change on you.
(function($) { var sbtb = { log: function(message) { $("#log").suspend(" ").suspend(bulletin); }, cast: [ { firstName: "Zack", lastName: "Morris", isExcited: false }, { firstName: "Kelly", lastName: "Kapowski", isExcited: truthful }, { firstName: "Lisa", lastName: "Turtle", isExcited: true }, { firstName: "Screech", lastName: "Powers", isExcited: false }, { firstName: "A.C.", lastName: "Slater", isExcited: fake }, { firstName: "Jessie", lastName: "Spano", isExcited: true }, { firstName: "Richard", lastName: "Belding", isExcited: simulated } ], soExcited: function() { // store this in that so we don't get dislocated later on when // our the context of "this" changes out from underneath u.s. var that = this; // use "that" to go a reference to the cast on this object $.each(that.cast, function(idx, actor) { // call the log part if (thespian.isExcited) { that.log(role player.firstName + " " + actor.lastName); // the value of "that" doesn't change - it's still the object } }); } }; sbtb.soExcited(); }(jQuery));
four. Stop Using ALL THE jQUERIES
jQuery has steadily kept increasing in size. This is only natural as new functionality is added. Even though the size has steadily been reduced since i.8.3, Information technology'south led to some decry from the community claiming information technology "unsuitable" for mobile development due to it's sheer mass.
However, jQuery is non an all or nothing library anymore. jQuery at present supports custom builds. I know it's really tempting to utilise the jQuery CDN and merely rock on, but it is important to retrieve nigh all the code that yous are asking your users to download that they might non even need. That's no big deal on a desktop, just bits get precious on mobile devices, and there is no indicate in sending downwards a bunch of lawmaking to support legacy browsers if your app is a mobile one.
You accept two choices here. You can head over to the GitHub site and create a custom build with Git. It'due south actually really easy and I had no issues getting it to work. But, if pounding out node commands is not your matter, John Resig tweeted most a spider web UI for custom builds the other day.
5. Stop Using jQuery…
…when you don't need to.
I got to a signal in my development career where the first affair that I did with any project was add together jQuery, even if I was just creating very simple projects and samples. I did this mainly and so that I could just use the DOM selection utilities. Back in the twenty-four hour period of older browsers, this was easier to justify, but modernistic browsers have this whole DOM selection matter already nailed downwards for yous.
Document.QUERYSELECTOR
If you lot are using at least IE version 8 and in a higher place, you lot can just map the $ to certificate.querySelector, which will return you the first matched chemical element from the selector. Y'all can pass any CSS selector to the function.
Note that IE eight only supports CSS 2.1 selectors for querySelector.
<div course="container"> <ul> <li id="pink">Pink</li> <li id="salmon">Salmon</li> <li id="blue">Blue</li> <li id="green">Green</li> <li id="carmine">Red</li> </ul> </div> <script> // create a global ' Attempt It Of course, there is no chaining when using the native "way" method, so item logs out "salmon" which is what the backgroundColor method returned. Having a DOM node is sometimes more than handy than having a jQuery wrapped one. For case, let'southward say we desire to get a reference to an image and modify information technology'southward source. Have a look at how you would do information technology with jQuery as opposed to a straight up DOM node.
// the jQuery manner $("#motion-picture show").attr("src", "http://placekitten.com/200/200"); // Vanilla JS with $ mapped to querySelector $("#pic").src = "http://placekitten.com/200/200";
The DOM object gives you direct admission to the "src" belongings of the image because you have a node of type "prototype" that has access that property. In the instance of jQuery, everything is a jQuery object, then you have to get through the attr office to set the epitome source.
The certificate.querySelector method only gets you i element. If y'all call that on a collection of elements, it will return yous but the first matched node. You tin use document.querySelectorAll to get the entire list.
Certificate.QUERYSELECTORALL
A neat trick is to map $ to querySelector (ane issue) and map $$ to querySelectorAll which will requite you lot all matched DOM elements. The tricky part of this is that querySelectorAll returns a node list which isn't terribly helpful. Yous are probably going to need this every bit an array which yous tin slice up. Yous can catechumen the node listing to an array by using Array.prototype.slice.call(nodeList).
<div class="container"> <ul> <li id="pinkish">Pink</li> <li id="salmon">Salmon</li> <li id="blue">Blueish</li> <li id="green">Light-green</li> <li id="red">Cerise</li> </ul> </div> <script> // custom lightweight selector implementation // nickname: dolla window.$ = role(selector) { return certificate.querySelector(selector); }; window.$ = office(selector) { var items = {}, results = [], length = 0, i = 0; // this doesn't work on IE 8- and Blackberry Browser results = Array.prototype.piece.call(document.querySelectorAll(selector)); length = results.length; // add the results to the items object for ( ; i < length; ) { items[i] = results[i]; i++; } // add some additional properties to this items object to // go far look like an array items.length = length; items.splice = [].splice(); // add together an 'each' method to the items items.each = function(callback) { var i = 0; for ( ; i < length; ) { callback.call(items[i]); i++; } } return items; }; // end custom selector API (function() { // select the green item and crank upwards the font size $("#green").style.fontSize = "2em"; // select item1 by id and modify it's background color to salmon $("li").each(role() { this.style.backgroundColor = this.id; }); }()); </script>
Endeavor It
Notation that converting a nodeList to an array is not supported on IE eight and below.
At this point you may recollect to yourself, "That'due south a lot of JavaScript to write when I can just include jQuery bro," and that'southward off-white. This could be reduced no dubiousness, only jQuery puts so much convenience on objects and collections that when you start rolling without it, you lot come across what sort of code it takes to recreate only a small piece of it – and this implementation doesn't even support IE 8 and below or Blackberry browser. Depending on what your awarding needs to practice though, it could be far less code than including jQuery.
Leland Richardson and Jonathan Sampson helped me add a few more than features to and clean up the above code. Nosotros created a repo chosen "Dolla". It's not meant to be a replacement for jQuery in any way whatever, but rather a chance for united states of america to learn what it'due south like to say "I don't demand jQuery". Information technology'southward a fair bit more than code than you might conceptualize.
Stop Reading Articles That Tell You To Stop Doing Something
Seriously though. This is just to underscore the betoken that these are suggestions, not absolute rules of law. There are a yard ways that you can debate and or justify any of these items. This is merely to become you thinking about how you use jQuery and how you might be able to do information technology amend than you practise at present.
And then enjoy jQuery, be happy, and stay in school.
variable
window.$ = part(selector) {
return document.querySelector(selector);
};
(function() {
// select item1 by id and change it's background color to salmon
var detail = $("#salmon").way.backgroundColor="salmon";
console.log(item);
}());
</script>
Attempt It
Of grade, at that place is no chaining when using the native "style" method, so item logs out "salmon" which is what the backgroundColor method returned.
Having a DOM node is sometimes more than handy than having a jQuery wrapped one. For instance, permit's say we desire to become a reference to an image and change information technology's source. Have a look at how you would do it with jQuery as opposed to a directly up DOM node.
The DOM object gives you lot straight access to the "src" property of the paradigm because y'all have a node of type "image" that has admission that property. In the case of jQuery, everything is a jQuery object, so you have to get through the attr role to gear up the image source.
The document.querySelector method only gets you ane element. If you lot call that on a drove of elements, information technology will return yous only the first matched node. You can use document.querySelectorAll to get the entire listing.
Certificate.QUERYSELECTORALL
A neat fox is to map $ to querySelector (1 result) and map $$ to querySelectorAll which volition requite you all matched DOM elements. The tricky part of this is that querySelectorAll returns a node list which isn't terribly helpful. You are probably going to need this as an array which you can piece upwards. Yous can convert the node list to an array past using Array.image.piece.call(nodeList).
Try Information technology
Note that converting a nodeList to an array is non supported on IE 8 and below.
At this point you may retrieve to yourself, "That'southward a lot of JavaScript to write when I can just include jQuery bro," and that'southward off-white. This could be reduced no incertitude, only jQuery puts so much convenience on objects and collections that when you start rolling without it, you encounter what sort of lawmaking it takes to recreate just a small piece of it – and this implementation doesn't fifty-fifty back up IE 8 and beneath or Blackberry browser. Depending on what your application needs to do though, it could be far less code than including jQuery.
Leland Richardson and Jonathan Sampson helped me add a few more features to and clean upward the above lawmaking. We created a repo chosen "Dolla". It's not meant to be a replacement for jQuery in whatsoever manner whatsoever, but rather a chance for us to learn what it's like to say "I don't need jQuery". It's a fair fleck more code than you might anticipate.
Cease Reading Manufactures That Tell You To Stop Doing Something
Seriously though. This is but to underscore the point that these are suggestions, non absolute rules of police force. At that place are a k means that y'all can argue and or justify any of these items. This is merely to become you thinking nearly how you use jQuery and how y'all might be able to practice it better than you practice at present.
So enjoy jQuery, exist happy, and stay in school.
Burke Kingdom of the netherlands is a spider web developer who hangs out in Nashville, TN even though he doesn't really care for land music. Previously, he was an Adobe Flex programmer and is currently a JavaScript / HTML5 fanatic working as a Developer Evangelist for Kendo UI. You can find him blogging for Kendo UI and on his personal weblog A Shiny New Me. He hangs out on twitter as @burkeholland and avoids Facebook altogether. He has an obsession with Instagram and in one case updated everyone's last name in the corporate ERP database to "Kingdom of the netherlands". He is not a fan of SQL.
Follow Burke on Twitter
Visit Burke's site
Source: https://modernweb.com/5-things-stop-jquery/
0 Response to "Jquery Call Default Load Function Jquery Call Document Ready Again"
ارسال یک نظر