Reputation: 6539
In my one of the PHP project, part of it done by some other people. All the js scripts are loaded in footer file. The html closes at the footer file. How Can I use jquery functions before the inclusion of footer file ?. Since using it after the footer file will show it after the closing of html. When I tired to use jquery functions before the footer I get the js error $ not defined etc.. I have searched many similar questions but couldn't find a solution. I can't change the file inclusion order currently since some other people have done it. Any help will be appreciated.
Upvotes: 0
Views: 1711
Reputation: 2011
I sometimes did something like this:
function JQueryManager(callback, thisArgument) {
this.execute = function() {
if (typeof jQuery == "undefined") {
console.log("Waiting for jQuery...");
var self = this;
var selfArgs = arguments;
setTimeout(function() {
self.execute(selfArgs)
}, 100)
} else {
console.log("Found jQuery. Version: " + jQuery.fn.jquery);
callback.apply(thisArgument, arguments)
}
}
}
function myCallback(results) {
alert("found " + results.length + " results")
}
var jQueryManager = new JQueryManager(myCallback);
jQueryManager.execute($("div"));
That allows you to execute a callabck function when jQuery is available
EDIT: fixed some copy-paste errores
Upvotes: 1
Reputation: 125
this code will only run properly in modern browsers (IE > 8)
<div class="jq"></div>
<script>
document.addEventListener('DOMContentLoaded', function(){
$('.jq').html('working');
});
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Example - http://jsfiddle.net/2mmdrega/
Upvotes: 1
Reputation: 39777
If, like you mention, you have absolutely no control over where jQuery scripts are included, you can set timer to check when jQuery is ready, e.g.:
<script>
var i = setInterval(function() {
if ($) {
clearInterval(i);
$(document).ready(function(){
alert('Ready!');
})
}
}, 100)
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
But otherwise - if you can control it - include them before your code.
Upvotes: 2