Reputation: 511
I'm trying to write a bookmarklet which involves dynamically adding two script tags, one for jQuery and the other for a js script written in jQuery. The problem I'm having is that even though I add the jQuery script first, js script isn't able to be read because the browser says that jQuery is undefined. I know that the error is that jQuery is still being loaded as the browser adds my js script and as a result, the browser doesn't recognize the jQuery in the js script when it is executing the js script. Is there anyway to delay the adding of the js script tag until after jQuery is completely loaded?
Thanks!
Upvotes: 1
Views: 2271
Reputation: 180
The first thing that most Javascript programmers end up doing is adding some code to their >program, similar to this:
window.onload = function(){ alert("welcome"); }
Inside of which is the code that you want to run right when the page is loaded. Problematically, however, the Javascript code isn't run until all images are finished downloading (this includes banner ads). The reason for using window.onload in the first place is that the HTML 'document' isn't finished loading yet, when you first try to run your code.
Hopefully this information helps, -pulled from JQuery tutorial!
Upvotes: 1
Reputation: 11220
How do your script look like?
You should encapsulate everything you do in the script in a function, which you then call from the document.
For instance put everything in the function myJqueryFunction()
then call it with:
$(document).ready(function(){
myJqueryFunction();
});
That makes your code only to execute once jQuery have fully loaded.
Alternatively, you should be able to execute your script using Ajax, but keep in mind that your script have to be served from the same domain as the document, otherwise it will not have access to the DOM.
$(document).ready(function(){
$.ajax("url to your script", {dataType:"script"});
});
Upvotes: 2
Reputation: 154818
You can use a script loader like LABjs
: http://labjs.com/. It supports deferring other scripts using wait
.
$LAB
.script("jquery.js")
.wait()
.script("script.js");
Upvotes: 0