开发者

An other way to load a js file in js code

I opened a javaScript file in a javaScript time....

document.write("<script src='newnote.js' type='text/javascript'></script>");

is there an other way to load the js in js code..?

开发者_StackOverflow社区

(this file is for loading a popup menu js code , which is loaded after delay by clock js code ... so i want an othe way to loaded it)


When opening a JS file, its code is executed at once - functions are created, code is run, events are set. The only way to 'unload' a Javascript file is to manually undo all the code that has been run as a result of loading the unwanted file: setting all new functions, variables and prototype aditions to undefined (e.g. window.badFunction = undefined, unset all events, remove all new DOM elements..

If you wanted to unload another JS file every time when opening a page, it could in theory be done, but not very easily and if the loaded JS file should change, you would have to update your invalidating file.


What you did isn't like opening a local file in a programming language like C++ or Java. You don't need to close anything.


Is it possible that the script that you are adding to the page (in this case newnote.js) is causing the error you are experiencing?

Instead of the line you used starting with document.write use this instead:

var newnote = document.createElement('script');
newnote.src = "newnote.js";
newnote.type = "text/javascript";
document.documentElement.firstChild.appendChild( newnote );

If you still get your quotes error, then the code inside of newnote.js is messed up.

Don't think this was really what you were asking, but if you used the code I listed above you could then remove this file from your page by calling this:

document.documentElement.firstChild.removeChild( newnote );

One more thought:

If your path to newnote.js is not correct (because it is not in the same directory as the calling page) then the server would return a 404 error page instead of the file. If your browser tried to execute it like javascript, it could throw an error. Try supplying the full URL: http://yoursite.com/js/newnote.js or a root relative one: /js/newnote.js


you are not opening a javascript file, in fact you cannot open any file from local file system, so there is no question of closing. You are inserting a script tag replacing all contents of the document. This would result in fetching newnote.js using the current url with newnote.js replacing anything after last slash.


To include a script you could try this:

var s = document.createElement('script');
s.src = 'newnote.js';
s.type = 'text/javascript';
var head = document.getElementsByTagName('head')[0]
head.appendChild(s);

or like that:

document.write("<script type='text/javascript' src='newnote.js'><\/sc" + "ript>");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜