I have tried 3 suggestions found in other questions on the site but none seem to wo开发者_开发百科rk for me and I'm not sure why.
// #1
var imported = document.createElement('script');
imported.src = '/path/to/imported/script';
document.getElementsByTagName('head')[0].appendChild(imported);
// #2
// jQuery
$.getScript('/path/to/imported/script.js', function()
{
// script is now loaded and executed.
// put your dependent JS here.
});
// #3
document.write( '<script language="javascript" src="myotherscript.js" />' );
The file I am trying to include is basically a massive file with variables declared like so:
var agent = [
"csv",
"drawfile",
"excel",
"flash",
"hangul",
"html",
"image",
"msword",
"ooxml",
"pdf",
"ppt",
"txt",
"wmf"];
Any ideas on what could be causing the problem?
UPDATE
Just an update to say that the JS file that I'm trying to include is generated dynamically from a database, so avoid regular expressions to add and remove the same bit of code constantly I have it stored in a serparate file.
The variables concerend are used to populate a dynamic drop down list with the values, so by not working I mean no values in the dropdowns :(
I would use require plugin for now I think jquery will have this in the next core release 1.6
If the sole purpose is to include another javascript file to declare a bunch of variables and their values into the global scope, why not just <script type="text/javascript" src="myotherscript.js"></script>
in the head of your html document before your other script source includes?
Edit:
The problem is that you cannot define global variables from within a method. You do have the plausible option of encapsulating your whole script file (or at least the affected portions) in a jQuery ajax function which evaluates your included file first thing. That would leave your included variables in the correct scope. Here is what I mean...
$.ajax({
url: 'path/to/included/file',
success: function(msg) {
eval(msg); // This is where your included variables are in regard to scope
// This is where you would paste all of your dependent functions and whatnot
}
});
// Outside of the ajax method, you won't be able to use your included properties
var getScript = function(jsPath) {
$.ajax({
dataType:'script',
async:false,
cache:true,
url:jsPath
});
};
http://requirejs.org/ is the most popular for this kind of problem
Thank you everyone for your help but I think the cause of the errors was some characters that needed escaping within the variables.
Martin
精彩评论