I'm trying (and failing), to get scripts to load in the header of certain posts before the rest of the page loads. Some of my posts have embeds that require scripts to work, but my makeshift code below is not working properly.

This AJAX call is successfully being sent, the scripts are being filtered from the received data, but for some reason, my AJAX call is not appending these scripts to my head element in my HTML code. So where have I gone wrong?

(function ($) {
    $(document).ready(function () {

      var $mainContent = $(".main");
      var value;
      $this = '';

      $(document).on("click", "#posts a", function (e) {
        $this = $(this);
        value = $this.attr("href");

            url: value,
            type: 'POST',
            dataType: "html",
            error: function (data) {
            success: function (data) {
              var dom = $(data);
              dom.filter("script").each(function () {
                if (this.src) {
                  var script = document.createElement('script'),
                    i, attrName, attrValue, attrs = this.attributes;
                  for (i = 0; i < attrs.length; i++) {
                    attrName = attrs[i].name;
                    attrValue = attrs[i].value;
                    script[attrName] = attrValue;
          }).done(function (data) {
            var dom = $(data);

This code worked for me:

    success: function (data) {
      var dom = $(data);
      scripts = dom.filter('script').each(function () {
        script = $(this);
      //...more code
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.