6 fast jQuery Tips: More basic Snippets
Posted 2009-01-07 in JavaScript by Johann.
Still hungry for jQuery tips? After the first and second session, here are more snippets.
Force a Page Reload
This will forcefully reload the current page. No jQuery needed here.
location.reload(true);
If your content might be cached by proxy servers and your URL has no query string, try this:
location.replace( location.href.replace(/\?.*$/, '') + '?' + Math.random());
Many ad networks use this trick to ensure that ad tags are never cached.
Try it: Reload this page.
Reload an Image
There is no reload
or replace
method for images. The src
property can be set in the same way as the location.href
property though.
with($('#image')) { src = src.replace(/\?.*$/, '') + '?' + Math.random(); }
Try it: Reload this awesome photo of my awesome tour to the Schildenstein. In Firebug, you will see the new image being loaded.
Replace a <div> with jQuery
The easiest way, pointed out by Paul, is to use the replaceWith method.
$('#thatdiv').replaceWith('<div>fnuh</div>');
A more confusing way is to insert the new element after the target element’s previous element and then remove the target element. The with statement makes it shorter.
with ($('#thatdiv')) { with (prev()) { after('<p>Your new content goes here</p>'); } remove(); }
Try it: Replace this element with something completely different.
Verify if an Element is empty
if ($('#keks').html()) { // Do something to remedy the situation }
Test it: Is this element empty?
Append or Add HTML to an Element
One of the nicest things about jQuery that most methods are named what you’d expect them to be named.
$('#lal').append("<b>lol</b>");
Test it: Append your eBay username and password to this.
When to load jQuery on the page?
I assume most people include the jquery.js
in the <head>
portion of a page – at least I do. But unless you write CSS overrides on the page from JavaScript (document.write('<style>/<script>…')
), putting it at the bottom improves performance.
I hope you have enjoyed these snippets. If you did, get updates via my news feed.
3 comments
Automate JavaScript compression with YUI Compressor and /packer/
Posted 2007-12-17 in JavaScript by Johann.
JavaScript compression should be one of the finishing touches to your website, like optimizing your images with OptiPNG and other automated optimizations. Shrinking the size of your JavaScript code will make your site load faster and your visitors happier.
In this blog entry, I will show you how to automatically compress your various JavaScript source files into one single compressed file. The tools I will use is the YUI Compressor and Dean Edward’s /packer/.
Prerequisites
- Create the following folders:
js
for the compressed JavaScript.js-in
for the input files.packer
for /packer/.yui
for YUI Compressor.
- Download YUI Compressor.
- Extract
yuicompressor-2.2.5.jar
to theyui
directory. - Download Rhino.
- Extract
js.jar
topacker
. - Download
packer.js
(originally written by David McNab) topacker
.
Create the batch file
Copy the following code to a file called pack.bat
and save it to your js
folder.
type ..\js-in\* > jb.js java -jar ..\yui\yuicompressor-2.2.5.jar -o jb-yui.js jb.js cd ..\packer java -jar js.jar packer.js ..\js\jb-yui.js ..\js\jb.js cd ..\js del jb-yui.js
(Replace jb
with the name of your site or something similar.)
Tips
- If you use multiple input files, you should name them like this:
10-jquery-1.2.1.js
20-jquery.inc-5.js
30-menu.js
2 comments
JavaScript Compression Alternatives to /packer/
Posted 2008-03-03 in JavaScript by Johann.
Photo by capsicina. Some rights reserved.
Squeezing the last bits out of your JavaScript files? Then you probably know /packer/. Maybe you even use it with YUI to automatically compress multiple JavaScripts into one file.
Recently, I discovered new alternatives to /packer/ and decided to compare them.
JavaScript compressors
The two new JavaScript crunchers I test are
- JSIntegration, a Java-based JavaScript packer with a Java Swing frontend. I used the
JSA-20071021.jar
file. My settings were: “Syntax compression” on, “text compression” on, “Compatible(IE5,NS3)” on, “auto confuse” off. The header comment was removed. - JavaScript Utility V2 by Patrick J. O'Neil. I used the ISO-8859-1/UTF-8 setting.
Test files
The files I compressed were
- The JavaScript for johannburkard.de. 73716 B uncompressed, 43170 B after YUI.
- jQuery 1.2.3. 96763 B uncompressed, 53807 B after YUI.
I started with YUI compressed versions.
Results
johannburkard.de JavaScript
- 23223 B (31 %) – JavaScript Utility
- 25711 B (34 %) – JSA
- 27988 B (38 %) – /packer/
jQuery 1.2.3
- 25877 B (27 %) – JavaScript Utility
- 28646 B (30 %) – JSA
- 29606 B (31 %) – /packer/
Decompression times
While packed JavaScript files make your pages load faster, the browser still has to decompress the file. I didn’t benchmark all packers but the previous version of JavaScript Utility was about twice as slow as /packer/. After a recent update, JavaScript Utility is now about as fast as /packer/ (some informal performance numbers, OpenOffice document).
Edit: Neil Roberts suggested that I try ShrinkSafe instead of YUI. Here are the results:
johannburkard.de JavaScript
24689 B (33 %) – ShrinkSafe, then JavaScript Utility.
jQuery 1.2.3
27469 B (28 %) – ShrinkSafe, then JavaScript Utility.
3 comments
Google Analytics ga.js Tracking Best Practices
Posted 2010-09-08 in JavaScript by Johann.
_gat._anonymizeIp()
- Google Analytics Search Engine Extension.
_trackPageview(location.pathname)
if you don’t use query parameters._trackPageview(location.pathname.replace(/;jsessionid=[^?]+/,'')
if you use session IDs. Over time, a lot of junk ends up in the query string and that might skew content reports.- Track positive and negative goals (anything that means the goal can’t be reached) in one goal set and track the positive goals one more time in another goal set. For media.io, a negative goal would be that the file couldn’t be converted.
_setDetectFlash(false)
because Flash is dead.- Google’s async ga.js syntax is stupid (but inevitably so). Use the
_gaq.push(function() { … });
syntax. - Any interaction in a form should probably be tracked using virtual page views instead of event tracking.
- Always use
_createTracker('UA-1234-12', 't')
once in the page and_getTrackerByName('t')
in event handlers._createTracker
should be used only once. - Set up a second profile for each domain that filters only search traffic (or whatever traffic you prefer). You can’t use segments when comparing date ranges with a filter and that is a workaround.
- Create a “branded traffic” segment for search terms that contain your brand name. Keep in mind people are creative when typing names so you will need to dig into your keywords first. For media.io, the segment filters
media\W*[1i]o
. - Create an “non-branded traffic” segment for search terms that don’t contain your brand name (see 10).
_setAllowAnchor(true)
so that you can link by using anchors instead of query strings. Can avoid duplicate content issues._setVisitorCookieTimeout(5270400000)
. This sets the persistent GA cookie expiration to 61 days instead of the default two years. I’ve never seen any substantial activity past two months.
Pages
Page 1 · Page 2 · Page 3 · Page 4 · Page 5 · Next Page »
Subscribe
RSS 2.0, Atom or subscribe by Email.
Top Posts
- DynaCloud - a dynamic JavaScript tag/keyword cloud with jQuery
- 6 fast jQuery Tips: More basic Snippets
- xslt.js version 3.2 released
- xslt.js version 3.0 released XML XSLT now with jQuery plugin
- Forum Scanners - prevent forum abuse
- Automate JavaScript compression with YUI Compressor and /packer/