How to get the dynamically inserted JavaScript scripting code running.

Source: Internet
Author: User
Tags cdata eval execution return script tag
javascript| Insert | dynamic | script

First of all, there are many ways to declare a method, both directly and indirectly, and only the two modes in general are listed:
Let's say the code we're loading is a.js:
var foo=function () {
document.write ("I am a.js content foo () function");
};

One. Directly inserting SRC, this method is simple but straightforward, but has limitations,
1)

<script>
var x=document.createelement ("SCRIPT");
X.src= "A.js"; X.defer=true;
document.getElementsByTagName ("Head") [0].appendchild (x);
Foo ();
</script>


The code above is placed inside the head tag, and most of the time it is executed with an error, the message: Error: Missing object
This is caused by the dynamic creation of the object script, which is not yet fully loaded in the a.js. Execute the following code and you'll find out why.

<meta http-equiv= "Content-type" content= "text/html; charset=gb2312 ">
<title>never-online Dynamic Code Test page</title>
<body>
<pre>

The meaning of readystate
-Uninitialized: The script object has just been created and the script code is not loaded;
-Loading: script code loading;
-Loaded: Script code completes read, but has not yet begun to explain execution;
-Interactive: Interpretation of the implementation process;
-Complete: script has been completed.

</pre>
<div id= "Viewer" ></div>
<script type= "Text/javascript" ....

Window.onerror=function (msg,url,line) ... {
document.getElementById ("Viewer"). innerhtml+= ' <p style= ' color:red ' > Error: ' +msg+ ' line: ' +line+ ' </p> ';
return true;
}

function bar (u) ... {
var x=document.createelement ("SCRIPT");
X.src=u;
X.defer=true;
document.getElementsByTagName ("Head") [0].appendchild (x);
}
Bar ("A.js");

(function getreadystate () ... {
var E=document.getelementbyid ("Viewer")
var x=true;
var a = document.getElementsByTagName ("SCRIPT");
for (var i=0; i<a.length; i++) ... {
if (a[i].readystate== ' complete ' && x!=false) x=true; else X=false
e.innerhtml+= (a[i].src?a[i].src+ ': ': ' Noname: ') +a[i].readystate+ "<br/>";
}
e.innerhtml+= "if (x) window.cleartimeout (Window.timer); Else
Window.timer=window.settimeout (' getreadystate () ', 1000);
}());

Foo ();

</script>
<script type= "Text/javascript" ....
<! [cdata[
Foo ();
]]>
</script>
</body>


The initial values are:
A.js:loading
Noname:interactive
We can know that a.js is still in the loading state, and it is certainly wrong to execute Foo (). But in the next script tag execution, A.js's readystate is complete, so the function of Foo () can be executed. From this, I recommend that you can simply use the dynamically generated script tag method to add JS URL.
The workaround is as follows
1) Use Window.settimeout method to execute, estimate a.js already loaded, just perform a.js function. This method is still not insured

<script>
var x=document.createelement ("SCRIPT");
X.src= "A.js"; X.defer=true;
document.getElementsByTagName ("Head") [0].appendchild (x);
Window.settimeout (' foo () ', 1000);
</script>
2 Add a script tag to put the code to execute
<script>
var x=document.createelement ("SCRIPT");
X.src= "A.js"; X.defer=true;
document.getElementsByTagName ("Head") [0].appendchild (x);
</script>
<script>
One more script tag to place
Here the A.js readystate has been complete.
Foo ();
</script>

Second, with XMLHttpRequest and window.execscript dynamic implementation of a.js, the advantages of this method is more obvious, but the efficiency may be reduced, there is no test, interested friends can test their own speed.
The code is as follows:
<script language= "JavaScript" >
function bar (u) {
var X=window. Activexobject?new ActiveXObject ("MSXML2"). XMLHTTP "): New XMLHttpRequest ();
X.open ("Get", u,false);
X.send (NULL);
S=x.responsetext;
try {window.execscript (s)}catch (ex) {Window.eval (s)};//mozilla Window.eval is roughly the same as IE's Window.execscript method feature
}
Bar ("A.js");
Foo ();
</script>
But this method still has the flaw, namely the code in the A.js script has the Chinese situation, how to handle? That will often decode, and decoding is the soft rib of JS, if the use of VBS to decode, and then there is no compatibility. To see their specific application, I nevermodules in the download JS package used is the Window.execscript method to parse the code, so more can be matched with JS namespace application
Plus script decoding (using a VBS to decode):
<script type= "Text/javascript" >
<! [cdata[
function bar (u) ... {
var X=window. Activexobject?new ActiveXObject ("MSXML2"). XMLHTTP "): New XMLHttpRequest ();
X.open ("Get", u,false);
X.send (NULL);
S=parsescript (X.responsetext);
Try ... {Window.execscript (s)}catch (ex) ... {Window.eval (s)};
}
function Parsescript (jscode) ... {
---tocurrentcharset (), by Aimingoo decoding
Window.execscript (' +
' Function asc2unicode (n) ' +
' Asc2unicode = CHR (n) ' +
' End Function ' +

' Function safearray2str (body) ' +
' Safearray2str = CStr (body) ' +
' End Function ', ' VBScript ');

var r1 =/%u (..) (..) /g, r2 =/% ([8,9,a-f].)% (..) /g;
var Tounicode = function ($, $, $) ... {return Asc2unicode (parseint ($1+$2, 16))}
Tocurrentcharset = function (body) ... {
return unescape (SAFEARRAY2STR). Replace (R1, "%$2%$1"). Replace (R2, Tounicode));
}; Jscode=tocurrentcharset (Jscode);
Window.execscript (Jscode, ' JavaScript '); IE valid, VBS decoding
return jscode;
}

Bar (' A.js ');

Foo ();
]]>
</script>

In most cases, however, the second approach should have no problem, and the first method would have improved code if it were to be strictly enforced. For example, loading a.js content, the script itself again to parse and execute, but the complexity of the increase, so to have a very perfect solution, but also need to further discuss.
I will not write so much, just for a reminder, there is also a role to play.



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.