Home > Enterprise >  script-tag not firing after jQuery clone
script-tag not firing after jQuery clone

Time:10-26

I need to stop a script from being fired before a specific cookie has been accepted.

I've been using the code from https://github.com/jfeltkamp/cookies_demo to knock-out the script-tag:

<script type="text/plain" data-sid="extservice" src="https://ext-service.net/js/install_many_cookies.js" ></script>

I remove the type-Attribute with (after the cookie is accepted):

jQuery('script[data-sid="extservice"]').each(function() {
   var $replacement = jQuery(this).clone().removeAttr('type');
   jQuery(this).replaceWith($replacement);
});

The attribute is removed but the script isn't executed. Is there anything I can do do have the script-code executed?

CodePudding user response:

jQuery won't help you there (see reason below).

However, you can achieve what you want by using Element.replaceWith instead of $().replaceWith(). Or you could use outerHTML:

jQuery('script[data-sid="extservice"]').each(function() {
    var $replacement = jQuery(this).clone(true).removeAttr('type');
    jQuery(this)[0].replaceWith($replacement[0]);                    // <-- changed here
    // alternative: jQuery(this).replaceWith($replacement.prop('outerHTML'));
});

Plunker demo here.

For the reason why $().replaceWith() didn't work:

Loading and running scripts inside HTML content

(...)

As of 1.9, scripts inserted into a document are executed, but left in the document and tagged as already executed so they won't be executed again even if they are removed and reinserted.

(...) Code that attempts to load a script by cloning an existing script tag and injecting that clone into the document will no longer work, because the cloned script tag has already been marked as executed. To load a new script, use jQuery.getScript() instead.

  • Related