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?

Community
  • 1
  • 1
Nicros
  • 5,031
  • 12
  • 57
  • 101

2 Answers2

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
}
Prescott
  • 7,312
  • 5
  • 49
  • 70
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() { });
Paul Mendoza
  • 5,709
  • 12
  • 53
  • 82
  • 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. – Nicros Feb 16 '13 at 07:18
  • @jfriend00 But he has the problem of the $ not being available yet, right? – Paul Mendoza Feb 16 '13 at 07:22