0

I have a <script> that generates a both <style> and inline style attributes with !important tags. I'd like to remove all this styling.

My plan was to use a javascript onload callback (and some jQuery) to remove the <style> block and all inline style attributes — but I can't seem to select any of these elements. Here's what I've been toying with:

var script = document.createElement("script");

script.src      = "//script.path.js";
script.onload   = function(){

    $(this).parent().find("style").remove();
    $(this).parent().find("[style]").removeAttr("style");

};

$(target).append(script);

UPDATE

It seems that the elements generated by the <script> just aren't available in the DOM right away. If I use setInterval to check if the elements exist first, I can get this to work. I imagine there's a better way to do this though...

HWD
  • 1,547
  • 7
  • 36
  • 72

1 Answers1

0

According to this other question, you must append the script tag to the DOM before setting onload.

var script = document.createElement("script");
$(target).append(script);

script.src = "//script.path.js";
script.onload = function(){
  $(this).parent().find("style").remove();
  $(this).parent().find("[style]").removeAttr("style");
};

https://jsbin.com/minoyeyicu/edit?html,js,output

UPDATE: Having clarified that the issue is that the style tag/attributes haven't yet been applied to the DOM until after the downloaded script has executed, one alternative (depending on whether the loaded script is under your control), is to pass a callback parameter to the loaded script and have the loaded script execute the callback when it finishes executing (which is how the Google Maps API works). E.g.

script.src = '//script.path.js?callback=removeStyles'

In order to use the callback parameter from within script.path.js, something like this could be done.

Ruy Diaz
  • 3,084
  • 24
  • 36
  • this is correct, but your bin doesn't demonstrate the style tags being added into the document via the script. – HWD Mar 02 '20 at 23:09
  • Oh, I understand your issue now... Is the loaded script under your control? If so, you could specify a callback to execute at the end of the script (similar to how [Google Maps can use the value of a `callback` parameter](https://developers.google.com/maps/documentation/javascript/tutorial)) in the URL to execute the given method once it's ready to load. E.g. `script.src = '//script.path.js?callback=removeStyles'`. See [this answer](https://stackoverflow.com/a/4716930/302246) on how to use this parameter. – Ruy Diaz Mar 02 '20 at 23:44
  • Unfortunately, the loaded script is not within my control. – HWD Mar 03 '20 at 18:16