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 the script 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, 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 good to go. 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:
hack ie
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 conflict with the id or name of some tags in the original content. 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 chose the method of first creating a copy object of the external script and setting its defer attribute to true (this is to allow IE browser can execute correctly), and then use the appendChild method to insert this copy object into the 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, 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 known whether other versions of Opera have this problem.) In order to avoid these problems, I chose to insert it into the head.
Looking at the internal script, we can directly obtain the content of the internal script 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, scripts may be included in HTML comment tags, 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, however, 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 execute our own defined document.write and document.writeln. 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 position. 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 the internal script is executed with eval, 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).
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 is 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 the back of 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 problem is that scripts 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 Singaporean netizen Jason Li for the reminder).
2006-5-29 Update:
Added the function of using external script cache 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:
/* 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.coolcode.cn/?p=117
*/
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(/