I am writing a plugin for a cms that has jQuery embedded at the end of the html document.
I do dynamically define some variables in my template code like that:
<script>
var name = '<?php echo $nameTakenFromTheDatabase; ?>';
</script>
This code is part of my plugin and it is not embedded on every page. Thus, name is not defined on every page.
I also do have this Javascript Code in a separate file (that gets automatically added to the page end by the cms):
var MyNamespace = (function() {
MyClass = function(name) {
// Do something with name
}
return {
MyClass: MyClass
}
})();
If jQuery was embedded at the top, I'd do something like this in my template code:
<script>
var name = '<?php echo $nameTakenFromTheDatabase; ?>';
$(document).ready(function() {
new MyNamespace.MyClass(name);
});
</script>
However, with jQuery included at the bottom I can't do that ($ is not defined yet). I as well can't just add the jQuery-DomReady call to the separate code file, because this is executed on every page, but the name var is not initalized on every pages and breaks the code.
What can I do? Is the good old document.ready a wise approach?
You could define methods in you script, and execute them from the global javascript file.
If you do something like this in you page
<script>
var name = '<?php echo $nameTakenFromTheDatabase; ?>';
function runWhenReady(){
new MyNamespace.MyClass(name);
}
</script>
Then in you global file, which is added at the bottom of the page, you can do something like this:
$('document').ready(function() {
if (typeof runWhenReady != 'undefined') {
runWhenReady();
}
});
If you are creative, you could make 'runWhenReady' a collection of methods, which would always be loaded when page is ready.
EDIT I have added an example of using an array:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript">
// check if array is already created. This is necessary if it is possible to render multiple pages which uses the runWhenReadyFunctions collection.
if (typeof runWhenReadyFunctions == 'undefined'){
window.runWhenReadyFunctions = new Array();
}
runWhenReadyFunctions.push(function(){
$('#testDiv').text('hello world!');
});
runWhenReadyFunctions.push(function(){
$('#testDiv2').text('hello another world!');
})
</script>
<div id="testDiv"></div>
<div id="testDiv2"></div>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
if (typeof runWhenReadyFunctions != 'undefined') {
$.each(runWhenReadyFunctions, function(idx, func){
func();
});
}
</script>
</body>
</html>