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) {
e.preventDefault();
$this = $(this);
value = $this.attr("href");
$.ajax({
url: value,
type: 'POST',
dataType: "html",
error: function (data) {
console.warn(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;
}
document.getElementsByTagName("head")[0].appendChild(script);
}
});
}
}).done(function (data) {
var dom = $(data);
$mainContent.html(dom.find('.main').html());
});
});
});
})(jQuery);
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) {
e.preventDefault();
$this = $(this);
value = $this.attr("href");
$.ajax({
url: value,
type: 'POST',
dataType: "html",
error: function (data) {
console.warn(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;
}
document.getElementsByTagName("head")[0].appendChild(script);
}
});
}
}).done(function (data) {
var dom = $(data);
$mainContent.html(dom.find('.main').html());
});
});
});
})(jQuery);
This code worked for me:
success: function (data) {
var dom = $(data);
scripts = dom.filter('script').each(function () {
script = $(this);
$("head").append(script);
});
//...more code
}