When doing ajax programming, we often need to assign the page content obtained by xmlhttp to a container (such as p, span or td, etc.) through innerHTML. However, there is a problem here, that is, we will assign it to innerHTML If the page content contains scripts, whether they are external scripts or internal scripts, (1) may not be executed. Sometimes this problem is trivial and can even be ignored, but sometimes, this problem is very serious, and it is likely that our program will not get the expected results. So we need to solve this problem.
If you read MSDN, you will find that not all scripts inserted into innerHTML cannot be executed. If the script tag of this script contains the defer attribute, IE will execute these scripts correctly. But unfortunately, Moziila/Firefox and Opera don't do this. Regardless of whether the script tag has the defer attribute set or not, these browsers will not execute scripts inserted into innerHTML like IE.
But regardless of whether the script is executed or not, one thing we can be sure of is that these scripts are indeed inserted into innerHTML. If you don’t believe it, you can alert and take a look. But if you really alert, you may also find that there is an exception, that is, if the script is at the beginning of the innerHTML content, then the IE browser will ignore this script, but Moziila/Firefox and Opera will not .
Okay, the problem analysis is almost done, let’s see how to solve it.
The solution is actually very simple, that is, take out all the scripts inserted into innerHTML and execute them one by one. But we need to solve the above two problems first.
Let’s look at the first question first, how to avoid repeatedly executing scripts with the defer attribute in innerHTML in IE. This is easy, you just need to first determine whether the browser is IE, and then check whether the script to be executed has the defer attribute. It should be noted that when judging IE browser, we need to avoid being deceived by opera's browser recognition. We will see how this is done in the code below.
Next, let’s look at the problem of IE ignoring the script at the beginning of innerHTML. This is also easy to solve. Just append a piece of content that is not a script to the beginning of the content you want to insert into innerHTML and you're done. But don't try to append a tag with empty content, or spaces, carriage returns, line feeds, etc., it won't work and the script at the beginning will still be ignored. Don't try to append , although this can prevent the beginning script from being ignored, but this will still affect the display of the original content. Although you may not think it is obvious, for picky users, this may be intolerable. Therefore, in order to allow the additional content to prevent the opening script from being ignored without causing adverse effects, we will append this content:
Although the above content is of a certain length, it will not be displayed, and the inserted tag has no id or name, so it will not be the same as some tags in the original content. The id or name conflicts. However, there is one thing to note here. You must also determine whether it is IE, and then decide whether to add this content, because some other browsers may not support the display: none CSS modification (such as Opera Mini). If you add this This code will affect the final display effect.
Let’s take a look at how to take out the script and execute it.
Removing the script is easy, just use the getElementsByTagName method of the object where innerHTML is located. This method works for almost all container tags. After taking out the scripts, we need to determine whether they are external scripts or internal scripts one by one.
Let’s look at the external script first. If it is an external script, we have chosen the method of first creating a copy object of the external script and setting its defer attribute to true (this is so that the IE browser can execute it correctly ), and then use the appendChild method to insert this copy object into head. You may ask here, why not insert it into the object where innerHTML is located? Wouldn't it be better to insert into the object where innerHTML is? If you try it, you will know that if you insert it into the object where innerHTML is located, there will be no problem in IE browser, but there will be some problems in Mozilla/Firefox and Opera browsers. The problem is that if you do this on Firefox, the browser will stop responding (this is a test result on Firefox 1.5, it is not known whether other versions have this problem), and on Opera, the script will be executed twice inexplicably ( This is a test result on Opera 8.5. It is not yet known whether other versions of Opera have this problem). In order to avoid these problems, I chose to insert it into head.
Let’s look at the internal script. The content of the internal script can be obtained directly using the text attribute of the script object. Here we use the text attribute of the script object instead of the innerHTML attribute because in the Opera browser, the script object The innerHTML attribute is empty, and only the text attribute can be used to obtain the script content. To execute internal scripts, just use eval. However, the script may be included in the comment tags of HTML, so we need to remove the comment tags first, otherwise an error will occur in IE.
The above analysis seems perfect, but in fact there are still problems. One is the problem of document.write and document.writeln. This problem is on Blueidea. bound0 gives an idea, which is to replace it. The default document.write and document.writeln methods, but they use string replacement, so they are only effective for internal scripts, but not for external scripts. Therefore, I thought of a more general method, which is to directly replace document. write and document.writeln are redefined, so that whether internal scripts or external scripts are executed, we define document.write and document.writeln ourselves. However, there are also side effects, that is, these two functions can no longer be used in the current page as before. However, these two functions will generally not be used after the page is loaded, so here are the side effects caused by redefining them. The impact is minimal. But another problem is that despite this, we still cannot guarantee that the content output by document.write or document.writeln will be displayed in the most appropriate location. It just appends the content to the container where we place the content.
Another problem is caused by eval. One is the scope problem mentioned by hutia on Blueidea. The other problem is that if you use eval to execute an internal script, the internal script will be loaded before the external script is loaded. The execution started. To solve these two problems, you can use the window.setTimeout function to delay each script for a period of time before executing it. The delay time for external scripts can be set longer to ensure that it can be fully loaded, while for internal scripts, it can be set is very short, because the execution time of a script is usually very short, which can not only ensure that the scope will not change, but also basically guarantee that the script execution order will not change (this method is not necessarily good at ensuring the execution order. 100% effective. If the network is very busy, the external script may not be loaded within the set time, but at least it is much better than using eval directly).
——————————–
(1) Note: Here, we use the qualifier "may", because there is a situation where the script will be executed. In the following you This will be seen.
If implemented according to the previous method, most scripts can be executed normally. But if there is a defer attribute in the script, IE will run that code by itself (mentioned earlier), so it will disrupt the order of execution. In addition, the code written by document.write and document.writeln will be added to the end, not where the script is located, so this is also a problem.
In order to solve these two problems, we need to make some changes to the previous solutions. First of all, we cannot assign the content to innerHTML first and then retrieve the script through it. We need to directly analyze the content to retrieve the script. In addition, the HTML part other than the script cannot be directly assigned to innerHTML. After the script is executed, the original HTML content and the content written by document.writewriteln need to be merged together in order and then assigned to innerHTML. It should be noted here that we cannot partially Part of this content is connected to innerHTML because there may be half the content of the tag, in which case the browser is prone to errors. And you will see the page refresh repeatedly. If you put it into the buffer first and assign it to innerHTML for the last time, this problem will not occur.
In addition, the advantage of putting it in the buffer is that after the script is executed, you can check whether there is a new script in the buffer. If there is, then execute it recursively, so that document.write and document. The script written by writeln can also be executed.
2006-6-4 Update:
Fixed the problem that the script inserted into innerHTML cannot obtain the object inserted into innerHTML. (Thanks to netizen DE for the reminder).
Added a shared lock set for content in the same container, so that conflicts will no longer occur when continuously setting content in the same container. (Thanks to Singapore netizen Jason Li for the reminder).
2006-5-29 Update:
Added the use of external script caching function to improve the speed of loading the same external script for the second time.
2006-5-23 Update:
As reminded by enthusiastic user johnZEN, a shared lock has been added so that conflicts will no longer occur when setting the contents of multiple containers at the same time. .
As reminded by netizen udbjatwfn, the internal script execution scope error in IE has been fixed.
The following is my final implementation code:
Download: innerhtml.js
Copy code The code is as follows:
/* innerhtml.js
* Copyright Ma Bingyao
* Version: 1.9
* LastModified: 2006-06-04
* This library is free. You can redistribute it and/or modify it.
* http://www.php.cn/
*/
var global_html_pool = [];
var global_script_pool = [];
var global_script_src_pool = [];
var global_lock_pool = [];
var innerhtml_lock = null;
var document_buffer = "";
function set_innerHTML(obj_id, html, time) {
if (innerhtml_lock == null) {
innerhtml_lock = obj_id;
}
else if (typeof(time) == "undefined") {
global_lock_pool[obj_id "_html"] = html;
window.setTimeout("set_innerHTML('" obj_id "', global_lock_pool['" obj_id "_html']);", 10);
return;
}
else if (innerhtml_lock != obj_id) {
global_lock_pool[obj_id "_html"] = html;
window.setTimeout("set_innerHTML('" obj_id "', global_lock_pool['" obj_id "_html'], " time ");", 10);
return;
}
function get_script_id() {
return "script_" (new Date()).getTime().toString(36)
Math.floor(Math.random() * 100000000).toString(36);
}
document_buffer = "";
document.write = function (str) {
document_buffer = str;
}
document.writeln = function (str) {
document_buffer = str "n";
}
global_html_pool = [];
var scripts = [];
html = html.split(//i);
for (var i = 0; i < html.length; i ) {
global_html_pool[i] = html[i].replace(/ scripts[i] = {text: '', src: '' };
scripts[i].text = html[i].substr(global_html_pool[i].length);
scripts[i].src = scripts[i].text.substr(0, scripts[i].text.indexOf('>') 1);
scripts[i].src = scripts[i].src.match(/srcs*=s*("([^"]*)"|'([^']*)'|([^s]*)[s>])/i);
if (scripts[i].src) {
if (scripts[i].src[2]) {
scripts[i].src = scripts[i].src[2];
}
else if (scripts[i].src[3]) {
scripts[i].src = scripts[i].src[3];
}
else if (scripts[i].src[4]) {
scripts[i].src = scripts[i].src[4];
}
else {
scripts[i].src = "";
}
scripts[i].text = "";
}
else {
scripts[i].src = "";
scripts[i].text = scripts[i].text.substr(scripts[i].text.indexOf('>') 1);
scripts[i].text = scripts[i].text.replace(/^s*