0

So I have a static HTML page that I cannot edit and I need to add jQuery to it and then do some div manipulation (height) on document ready. I found this post which describes how to insert it into a page, which works great. I added that to my javascript file and it inserts it into the page. The problem is that I need to perform some actions on $(document).ready() on that same page, but it says that $ is undefined.

What I would like to do is something like this:

var script = document.createElement('script');
script.src = 'http://jqueryjs.googlecode.com/files/jquery-1.2.6.min.js';
script.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(script);

$(document).ready(function() {
   // Resize my div's to the browser window
});

But I can't seem to get it to work. Is this possible? How?

5
  • (offT) 1.2.6 is somewhat old, isn't it? Commented Feb 16, 2013 at 6:57
  • You would have to wait for the script to load before using jQuery. You can find how to do that with a simple google search. Commented Feb 16, 2013 at 7:03
  • @roXon Yes it is :) I just copied the code from the other post. I'm using the latest version. Commented Feb 16, 2013 at 7:15
  • @jfriend00 do you mean to use $(windows).load()? I did a simple google search and that's what I found. Link? Commented Feb 16, 2013 at 7:18
  • No, you have to actually monitor for when the script is loaded. Prescott's answer shows it. Commented Feb 16, 2013 at 7:26

2 Answers 2

2
var script = document.createElement('script');
script.src = 'http://jqueryjs.googlecode.com/files/jquery-1.2.6.min.js';
script.type = 'text/javascript';
script.onload = resize;                    //most browsers
script.onreadystatechange = function() {   //ie
    if (this.readyState == 'complete') {
        resize();
    }
}

document.getElementsByTagName('head')[0].appendChild(script);

function resize() {
   //code goes here
}
Sign up to request clarification or add additional context in comments.

Comments

0

This is due to the ready event firing before the JS jQuery file has loaded. Here is a good tutorial on how to do it.

http://www.ejeliot.com/blog/109

This isn't going to help your page performance though to load your jQuery like this. You should really try to minimize your JS and use as few requests as possible for the best user experience.

Also, you don't need to write

$(document).ready(function() { });

You can just write

$(function() { });

2 Comments

Awesome I will look at this. Page performance isn't really an issue in this specific case, I just need to get this functionality working.
@jfriend00 But he has the problem of the $ not being available yet, right?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.