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
Then in you global file, which is added at the bottom of the page, you can do something like this:
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: