0

I have a document I'm working on as part of a much larger site. A lot of scripts are loaded in automatically, but one is breaking things and I don't know how it's included. I can't remove it because it's needed elsewhere (it does event listeners), but it serves no purpose for the part of code I'm running other to cause a pointless page refresh which ruins the users' work (and then, only in chrome).

To that end, is there a way in javascript to turn off another source script, and then turn it back on later?

I don't have the option of modifying the target script itself or keep it from being initially included in the document.

3
  • 1
    nope sorry. there isn't much you can do. Commented Dec 15, 2015 at 0:16
  • 1
    Can you control what order the scripts load in? Commented Dec 15, 2015 at 0:17
  • @Bioto Unfortunately, no. Commented Dec 15, 2015 at 0:20

1 Answer 1

2

Sort of...

you can always store any JavaScript method inside a variable, replace it's implementation, do your own stuff and finally restore it.

From your question it is unclear if this might be a solution for your Problem, I just mention this because of all the "Not possible" comments.

https://jsfiddle.net/3grfL30s/

function alertSomething(cp){
  alert("TEST: " + cp);
}


alertSomething(1);
// from here i dont want alerts, no matter what code is calling the method
// backup method to "x" to restore it later.
var x = alertSomething;
alertSomething = function(){} //overwrite alertSomething to do nothing

//do my work, verify alertSomething is doing nothing
alertSomething(2);

//restore alert method
alertSomething = x;

//verify its working agian
alertSomething(3);

This would produce the alerts 1 and 3, even if 2 would have been called while your code is beeing executed.

For more complex methods or non-boolean execution conditions, the Proxy Pattern with additional "flags" can be useful (Example still boolean, but there could be multiple conditions):

https://jsfiddle.net/3grfL30s/1/

function alertSomething(cp){
  alert("TEST: " + cp);
}

var doIt = 1;
var originalAlert = alertSomething;
alertSomething = function(cp){
  if (doIt){
    return originalAlert.apply(this, arguments);
  }
}

alertSomething(1);
// in here i dont want alerts
doIt = 0;

//do my work, verify alertSomething is doing nothing
alertSomething(2);

//restore alert method
doIt = 1;

//verify its working agian
alertSomething(3);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, that's the best idea I've seen so far. Doesn't fully solve my problem, but definitely gets me a step closer. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.