Home Web Front-end JS Tutorial Implementation code to run script inserted into innerHTML_javascript skills

Implementation code to run script inserted into innerHTML_javascript skills

May 16, 2016 pm 07:28 PM
script

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:

Copy code The code is as follows:

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:
Copy the 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.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(/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*

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Replace String Characters in JavaScript Replace String Characters in JavaScript Mar 11, 2025 am 12:07 AM

Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

Build Your Own AJAX Web Applications Build Your Own AJAX Web Applications Mar 09, 2025 am 12:11 AM

So here you are, ready to learn all about this thing called AJAX. But, what exactly is it? The term AJAX refers to a loose grouping of technologies that are used to create dynamic, interactive web content. The term AJAX, originally coined by Jesse J

How do I create and publish my own JavaScript libraries? How do I create and publish my own JavaScript libraries? Mar 18, 2025 pm 03:12 PM

Article discusses creating, publishing, and maintaining JavaScript libraries, focusing on planning, development, testing, documentation, and promotion strategies.

How do I optimize JavaScript code for performance in the browser? How do I optimize JavaScript code for performance in the browser? Mar 18, 2025 pm 03:14 PM

The article discusses strategies for optimizing JavaScript performance in browsers, focusing on reducing execution time and minimizing impact on page load speed.

How do I debug JavaScript code effectively using browser developer tools? How do I debug JavaScript code effectively using browser developer tools? Mar 18, 2025 pm 03:16 PM

The article discusses effective JavaScript debugging using browser developer tools, focusing on setting breakpoints, using the console, and analyzing performance.

How to Build a Simple jQuery Slider How to Build a Simple jQuery Slider Mar 11, 2025 am 12:19 AM

This article will guide you to create a simple picture carousel using the jQuery library. We will use the bxSlider library, which is built on jQuery and provides many configuration options to set up the carousel. Nowadays, picture carousel has become a must-have feature on the website - one picture is better than a thousand words! After deciding to use the picture carousel, the next question is how to create it. First, you need to collect high-quality, high-resolution pictures. Next, you need to create a picture carousel using HTML and some JavaScript code. There are many libraries on the web that can help you create carousels in different ways. We will use the open source bxSlider library. The bxSlider library supports responsive design, so the carousel built with this library can be adapted to any

jQuery Matrix Effects jQuery Matrix Effects Mar 10, 2025 am 12:52 AM

Bring matrix movie effects to your page! This is a cool jQuery plugin based on the famous movie "The Matrix". The plugin simulates the classic green character effects in the movie, and just select a picture and the plugin will convert it into a matrix-style picture filled with numeric characters. Come and try it, it's very interesting! How it works The plugin loads the image onto the canvas and reads the pixel and color values: data = ctx.getImageData(x, y, settings.grainSize, settings.grainSize).data The plugin cleverly reads the rectangular area of ​​the picture and uses jQuery to calculate the average color of each area. Then, use

How do I use source maps to debug minified JavaScript code? How do I use source maps to debug minified JavaScript code? Mar 18, 2025 pm 03:17 PM

The article explains how to use source maps to debug minified JavaScript by mapping it back to the original code. It discusses enabling source maps, setting breakpoints, and using tools like Chrome DevTools and Webpack.

See all articles