To do this (unsupported by Microsoft!) I learnt the following technique from CRM Specialists:
1: var script = document.createElement('script');
3: script.src = '/_customscript/customscript.js';
4: script.onreadystatechange = OnScriptReadyState;
7: function OnScriptReadyState()
9: if (event.srcElement.readyState == 'complete')
11: // Perform onload script
What this guy does is doing an AJAX call, to get the js file.
It needs functionnames a-z, it cannot handle numeric values in the name of the function, but i will fix this before I will use it.
Otherwise I think it rocks! Async technique (no first time drawback)
1: function load_script (url)
3: var x = new ActiveXObject("Msxml2.XMLHTTP");
4: x.open('GET', url, false);
7: var s = x.responseText.split(/\n/);
8: var r = /^function\s*([a-z_]+)/i;
9: for (var i = 0; i < s.length; i++)
11: var m = r.exec(s[i]);
12: if (m != null)
14: window[m] = eval(m);
21: //perform onload scripts
As I mentioned numbers in the functionname caused the code to fail. So I changed the regex pattern in line 8 from listing 2 into:
1: var r = /^function\s*([a-zA-Z_0-9]+)/i;
With this regex pattern functions with numbers in the name also are added to the namespace. I added the uppercase A-Z not because functions with uppercase characters in the name where not added, but as a best practice. also you can never be sure browsers keep on using IgnoreCase as default setting.
As you can read in the comments, Marc-Andre uses the following pattern:
1: var r = /^(?:function|var)\s*([a-zA-Z_]+)/i;
He wants some vars (which he uses as constants) to be added to the namespace also, maybe I would add the 0-9 here also. anyway, I think it is a good suggestion to mention here.
Steve Le Mon made a very good suggestion and tried out a few things, he found a way around the parsing of the functions and/or vars and adding them to the current namespace.
I tweaked his code a little bit and ended up with the following:
1: function InjectScript(scriptFile)
3: var netRequest = new ActiveXObject("Msxml2.XMLHTTP");
4: netRequest.open("GET", scriptFile, false);
This technique removes the overhead of the parsing of the functions and vars so will perform faster.
My thoughts exactly...