Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling code which relies on jQuery before jQuery is loaded

I'd like to follow the general guideline of putting all JavaScript at the very bottom of the page, to speed up loading time and also to take care of some pesky issues with conflicting jQuery versions in a web app (Django).

However, every so often I have some code, code which depends on jQuery, but which must be further up on the page (basically the code can't be moved to the bottom).

I'm wondering if there's an easy way to code this so that even though jQuery is not yet defined the code works when jQuery is defined.

The following seems, I have to say, like overkill but I don't know of another way to do it:

function run_my_code($) {     // jquery-dependent code here     $("#foo").data('bar', true); } var t = null; function jquery_ready() {     if (window.jQuery && window.jQuery.ui) {         run_my_code(window.jQuery);     } else {         t = window.setTimeout(jquery_ready, 100);     } } t = window.setTimeout(jquery_ready, 100); 

Actually, I might need to use code more than once in a page, code that doesn't know about other code, so even this probably won't work unless I rename each jquery_ready to something like jquery_ready_guid, jquery_ready_otherguid and so on.

Clarification

Just so this is clear, I am putting the include to JavaScript (<script type="text/javascript" src="jquery.min.js" />) at the very bottom of the page, just before the </body>. So I can't use the $.

like image 267
Jordan Reiter Avatar asked Nov 28 '11 15:11

Jordan Reiter


People also ask

How do I make sure jQuery loaded first?

If you load jQuery in the header and all of your other script in a script block at the end of the body, you can be sure that jQuery is loaded before your other code. I try to put everything at the end of the body, with jQuery being the first script loaded.

Which code is used to load the framework of jQuery from the site of jQuery?

var script = document. createElement('script'); script. src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js'; script. type = 'text/javascript'; document.

How do you check is jQuery loaded or not?

Basically, the most reliable way to check if jQuery has been loaded is to check typeof jQuery — it will return "function" if jQuery was already loaded on the page, or "undefined" if jQuery hasn't been loaded yet.

Which jQuery function prevents the code from running before the loading of the document?

The Document Ready Event This is to prevent any jQuery code from running before the document is finished loading (is ready). It is good practice to wait for the document to be fully loaded and ready before working with it.


1 Answers

Simple use pure javascript version of $(document).ready();:

document.addEventListener("DOMContentLoaded", function(event) {      //you can use jQuery there }); 
like image 172
Paweł BB Drozd Avatar answered Oct 09 '22 05:10

Paweł BB Drozd