I remember some years ago I was working on a project in Yii Framework 1.1. It’s my preferred framework for PHP, mainly due to it’s speed. However the version of 1.1 I was working with at the time had a pretty bad flaw where AJAX responses sending back HTML/JS/CSS had this bad habit of replacing the existing JS scripts in the DOM. This tended to break the widgets I was using, which had registered various callbacks using the initially sent versions of those scripts. So when they got replaced, those callbacks (mainly click events) broke pretty spectacularly. This issue was fixed in version 2.0 of the framework. There was a hacky fix that I had found by someone who’s page now no longer exists. I dug out the old code I had stashed away in my repo and will post it below. In short it’s essentially a filter that blocks all incoming scripts from being loaded into the DOM if they already exist.

$.ajaxSetup({
global: true,
dataFilter: function(data,type) {
// only 'text' and 'html' dataType should be filtered
if (type && type != "html" && type != "text") {
return data;
}
var selector = 'script[src],link[rel="stylesheet"]';
// get loaded scripts from DOM the first time we execute.
if (!$._loadedScripts) {
$._loadedScripts = {};
$._dataHolder = $(document.createElement('div'));
var loadedScripts = $(document).find(selector);
//fetching scripts from the DOM
for (var i = 0, len = loadedScripts.length; i < len; i++) {
$._loadedScripts[loadedScripts[i].src] = 1;
}
}
//$._dataHolder.html(data) does not work
$._dataHolder[0].innerHTML = data;
// iterate over new scripts and remove if source is already in DOM:
var incomingScripts = $($._dataHolder).find(selector);
for (var i = 0, len = incomingScripts.length; i < len; i++) {
if ($._loadedScripts[incomingScripts[i].src]) {
$(incomingScripts[i]).remove();
} else {
$._loadedScripts[incomingScripts[i].src] = 1;
}
}
return $._dataHolder[0].innerHTML;
}
});

Categories: CodePHPYii

Leave a Reply

Your email address will not be published. Required fields are marked *

Bitnami