views:

61

answers:

1

Ladies and gents,

I have a CRM page which references 3 js files, (1x jQuery, 2x custom) all stored in the CRMInstall/isv/ folder.

On the form OnLoad method, I am loading each one and then using it to extend/customise the UI.

My inexperience with jQuery is obviously showing however!

The OnLoad code is below:

//jquery
var url = "/isv/jquery-1.4.2.js";
var scriptElement = document.createElement("<script src='" + url + "' language='javascript'>");
document.getElementsByTagName("head")[0].insertAdjacentElement("beforeEnd", scriptElement);


$(document).ready(function() 
{ 
 $.getScript("/isv/common.js", function() 
 {
  $.getScript("/isv/account.js", function() 
  {
   $(document).ready(function() 
   { 
    SetUpAccountForm();//call to account.js
   });
  });
 });
});

And this causes the following (using IE8):
First page load (no files in temporary internet files folder)

  • error when hitting the $(document).ready(function(){})

Second page load (all files now in temporary internet files folder)

  • page/loads functions fine

hit F5 (refresh)

  • error when hitting the $(document).ready(function(){})

Where am I going wrong? Is it because I am adding a reference to the jQuery script twice?

In both cases the error reads:

There was an error with this field's customized event.
Field:window
Event:onload
Error:Object expected
+1  A: 

I think the problem is that by the time you hit the $(document).ready function the first time, Jquery hasn't fully loaded.... inserting the script tag does not mean that the script is immediately ready for use...

The second time you load it, the js files are already in the cache so the loading is a lot faster, but when you hit F5, it re-loads everything from the server and you are back to the first case.

you could solve this by attaching a function to the onload event of the script node that you're inserting:

var url = "http://code.jquery.com/jquery-1.4.2.min.js";

var head = document.getElementsByTagName("head")[0];         
var scriptNode = document.createElement('script');
scriptNode.type = 'text/javascript';
scriptNode.src = url;
scriptNode.onload = jQueryLoaded;
head.appendChild(scriptNode);


function jQueryLoaded()
{
    $(document).ready(function() {
        $("#some").text("Jquery loaded!!")
    });
}
Jaime
I'll try this when I am back in the office tomorrow but that sounds spot on, thanks for the example code as well!
glosrob
Worked perfectly, thank you
glosrob