I use google code to defer loading javascript (google pages)
But I have some inline javascripts such as:
<script type="text/javascript">
$(function () {
alert("please work");
});
</script>
And this gives me:
Uncaught ReferenceError: $ is not defined
I think I need some function, which was triggered after jQuery was loaded and init my inline javascripts. But if there is another way, I will be glad.
EDIT:
Some of you are completely out of topic. Mahesh Sapkal was close.
With this code I have no error, but still don't work
<head>
<script type="text/javascript">
var MhInit = NULL;
// Add a script element as a child of the body
function downloadJSAtOnload() {
var element = document.createElement("script");
MhInit = element.src = "my_packed_scripts.js";
document.body.appendChild(element);
}
// Check for browser support of event handling capability
if (window.addEventListener)
window.addEventListener("load", downloadJSAtOnload, false);
else if (window.attachEvent)
window.attachEvent("onload", downloadJSAtOnload);
else window.onload = downloadJSAtOnload;
</script>
</head>
<body>
<script type="text/javascript">
MhInit.onload = function() {
console.debug("here");
};
</script>
</body>
If you are going to implement async loading of Javascripts, then it would be a better idea to not have inline Javascript which depends on the asynchronously loaded file.
I suspect that you are loading jQuery asynchronously, i.e. after the DOM content has loaded, so any inline scripts in your DOM dependent on jQuery will fail. In that case, you may want to use something like RequireJS to manage your JS dependencies, and load them asynchronously.
However, if you want to go for a simpler solution, I would suggest putting your JS libraries at the end of the DOM, and binding any dependencies to an
onload
handler.Something like this