jQuery remembering if a script was already injected?
Update: It's not really necessary to remove added scripts considering once they run you can't really erase or delete all of the effect they've had on the page.
This is going to confuse a lot of poeple so sit back, relax, and grab some coffee. Really try hard to understand this.
First I'm going to explain what I'm doing.
1.) Ajax requests data from php using specific ID.
2.) PHP responds with a script from the specific ID. 3.) Javascript injects those returned scripts into dom for the purpose of running.What I need help with: I want to ensure the same script doesn't get injected twice. So I could use the u开发者_C百科rl and somehow store that value somewhere. Then the javascript could check to see if that a script was already executed, and not run it.
Note: Don't recommend jQuery.getscript(); or anything like that.
xhr = jQuery.ajax({ url: 'getscript.php?id=something', dateType: 'json', method: 'GET', async:false}); xhr.success(function(json){ if(json.script) { var script = document.createElement("script"); script.type = "text/javascript"; script.text = json.script; document.body.appendChild(script); // remove from the dom document.body.removeChild(document.body.lastChild); delete UnusedReferencedObjects; } });
Just store a list of all script IDs that have been executed, and check against it every time you are about to execute a new script in your success function.
If you set an id on the script block you created you should simply be able to query against if the id is present on the dom.
Your ajax call would look like this.
var theId = "something";
xhr = jQuery.ajax({ url: 'getscript.php?id=' + theId, dateType: 'json', method: 'GET', async:false});
xhr.success(function(json){
if(json.script && $('#'+theId).length == 0) {
var script = document.createElement("script");
script.type = "text/javascript";
script.text = json.script;
script.id = theId;
document.body.appendChild(script);
// remove from the dom
document.body.removeChild(document.body.lastChild);
delete UnusedReferencedObjects;
}
});
Example on jsfiddle.
精彩评论