开发者

Canceling dynamic script by removing script tag doesn't work in FF

I'm adding dynamic script by creating a script tag, setting its source and then adding the tag to the DOM. It works as expected, the script is getting downloaded and executes. However 开发者_如何学Gosometimes I would like to cancel script execution before it was downloaded. So I do it by removing the script tag from the DOM.

In IE9, Chrome and Safari it works as expected - after the script tag is removed from the DOM it doesn't execute.

However it doesn't work in Firefox - script executes even if I remove it from the DOM or change it its src to "" or anything else I tried, I cannot stop the execution of a script after it was added to the DOM. Any suggestions? Thanks!


How about some sort of callback arrangement? Rather than have the dynamically added script simply execute itself when it loads, have it call a function within your main script which will decide whether to go ahead. You could have the main script's function simply return true or false (execute / don't execute), or it could accept a callback function as a parameter so that it can decide exactly when to start the dynamic script - that way if you had several dynamic scripts the main script could wait until they're all loaded and then execute them in a specific order.

In your main script JS:

function dynamicScriptLoaded(scriptId,callback) {
   if (scriptId === something && someOtherCondition())
      callback();
   // or store the callback for later, put it on a timeout, do something
   // to sequence it with other callbacks from other dynamic scripts,
   // whatever...
}

In your dynamically added script:

function start() {
   doMyThing();
   doMyOtherThing();
}

if (window.dynamicScriptLoaded)
   dynamicScriptLoaded("myIdOrName",start);
else
   start();

The dynamic script checks to see if there is a dynamicScriptLoaded() function defined, expecting it to be in the main script (feel free to upgrade this to a more robust test, i.e., checking that dynamicScriptLoaded actually is a function). If it is defined it calls it, passing a callback function. If it isn't defined it assumes it is OK to go ahead and execute itself - or you can put whatever fallback functionality there that you like.

UPDATE: I changed the if test above since if(dynamicScriptLoaded) would give an error if the function didn't exist, whereas if(window.dynamicScriptLoaded) will work. Assuming the function is global - obviously this could be changed if using a namespacing scheme.

In the year since I originally posted this answer I've become aware that the yepnope.js loader allows you to load a script without executing it, so it should be able to handle the situation blankSlate mentioned in the comment below. yepnope.js is only 1.7kb.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜