Anyway to load an external script once on an event in an all ajax web page?
The page i have is very simple, but all of the links are loaded with ajax, 开发者_运维问答what i am wondering is there anyway to load an external script once one of the links is clicked, but make sure that the script is only loaded once? Basically just for the sake of performance.
You can load an external script by creating a script
element and appending it to head
:
var script=$("<script>");
script.attr("type", "text/javascript");
script.attr("src", "some_external_script.js");
script.appendTo("head");
You can use a simple variable to make sure it's only included once.
var addedExternalScript=false;
// ...somewhere else where loadedExternalScript is still in scope...
if(!addedExternalScript) {
// load the script
}
// script is in the document
Note that having the script element in the document won't necessarily mean it's loaded. You may need to bind to the load
event if you want to know when the script has loaded.
Is this code helpful to you?
var s = document.createElement('script');
s.type = 'text/javascript';
s.async = true;
s.src = 'script.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(s);
I used this code before, and it worked:
var t=document;
var o=t.createElement('script');
o=t.standardCreateElement('script');
o.setAttribute('type','text/javascript');
o.setAttribute('src','http://www.example.com/js/jquery-1.3.2.js');
t.lastChild.firstChild.appendChild(o);
精彩评论