Queueing jQuery scripts before the library

When trying to queue jQuery scripts to run before loading the library itself, this usually results in that code not working. If you want to load jQuery at the end of your page (or asynchronously) but you may need to include jQuery within a template part way through the page the following code allows you attach and queue up scripts to run when jQuery initialises.

if ( ! window.deferAfterjQueryLoaded ) {
    window.deferAfterjQueryLoaded = [];
    Object.defineProperty(window, "$", {
        set: function(value) {
            window.setTimeout(function() {
                $.each(window.deferAfterjQueryLoaded, function(index, fn) {
            }, 0);
            Object.defineProperty(window, "$", { value: value });

        configurable: true

window.deferAfterjQueryLoaded.push(function() {
    //... some code that needs to be run

What this does is:

  1. Defines deferAfterjQueryLoaded  lazily, so you don't need to inject that into head .
  2. Defines a setter for window.$ . When jQuery loads, one of the last things it does is assign to the global $ variable. This allows you to trigger a function when that happens.
  3. Schedules the deferred functions to run as soon as possible after the jQuery script finishes (setTimeout(..., 0);) .
  4. Has the setter remove itself.

For complete cleanliness you could have the scheduled function remove deferAfterjQueryLoaded  as well.


This answer is provided from StackOverflow.

IE & CDN jQuery source fallback

<!--[if !IE]><!--><script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script><script>window.jQuery || document.write('<script src="/js/jquery-3.0.0.min.js"><\/script>')</script><!--<![endif]-->
<!--[if IE]><script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script><script>window.jQuery || document.write('<script src="/js/jquery-2.2.4.min.js"><\/script>')</script><![endif]-->

jQuery Get + Post returned headers

This snippet allows you to use the response headers from a $.get and $.post function.

Particularly useful if you return a PHP response with additional information for jQuery to handle. i.e: Custom Header: Could not connect to database.

$(function() {

	var result = $.get('index.php', function(data) {

		console.log ( result.getAllResponseHeaders() );
		console.log ( result.getResponseHeader('Date') );




Date: Tue, 18 Sep 2012 11:24:40 GMT
Content-Encoding: gzip
X-Powered-By: PHP/5.3.5
Connection: Keep-Alive
Content-Length: 2713
Server: Apache/2.2.17 (Win32) PHP/5.3.5
Vary: Accept-Encoding
Content-Type: text/html
Keep-Alive: timeout=5, max=98
Tue, 18 Sep 2012 11:24:40 GMT