简体   繁体   中英

Reliable way to use $( document ).ready() in jQuery

Let say in the middle of a page generation, eg PHP script, you need to attach some code with jQuery' ready, eg

$( document ).ready(function() {
    console.log( "hi!" );
});

The problem is, at this point, you don't know if jQuery has or has not been loaded , how to modify the above code so both cases will be handled?

Update: The reason I ask is I want to add some JS codes in a WordPress blog post, but the jQuery is loaded in the footer (which I cannot alter), so I want to reliable solution that work both when jQuery is loaded in the header and footer.

If you have only console.log() function inside of document ready :) (I mean no jQuery)

if(typeof window.jQuery === "undefined") {
  window.onload = function () {
    console.log("hi!");
  }
} else {
  jQuery(document).ready(function() {
    console.log("hi!");
  });
}

Else ( UPDATE )

var j = document.createElement('script');
j.type = "text/javascript";
j.url = "url/to/your/jQuery";
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(j, s);
/** then your code */

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM