JavaScript - How do I make sure a jQuery is loaded?
javascript, jquery
Solution
The jQuery library should be included in the `<head>` part of your page:
<script src="/js/jquery-1.3.2.min.js" type="text/javascript"></script>
Your own code should come after this. JavaScript is loaded linearly and synchronously, so you don't have to worry about it as long as you include the scripts in order.
To make your code execute when the DOM has finished loading (because you can't really use much of the jQuery library until this happens), do this:
$(function () {
// Do stuff to the DOM
$('body').append('<p>Hello World!</p>');
});
If you're mixing JavaScript frameworks and they are interfering with each other, you may need to use jQuery like this:
jQuery(function ($) { // First argument is the jQuery object
// Do stuff to the DOM
$('body').append('<p>Hello World!</p>');
});
Problem
I have a web page. When this web page is loaded, I want to execute some JavaScript. This JavaScript uses JQuery. However, it appears that when the page is loaded, the jQuery library has not been fully loaded. Because of this, my JavaScript does not execute properly. What are some best practices for ensuring that your jQuery library is loaded before executing your JavaScript?