Dynamic JS, dynamic style of "senior" notes

Source: Internet
Author: User

Read
"JavaScript advanced Programming"---standing on the shoulders of giants

Dynamic JS, dynamic style is the page load does not exist, but in the future through the DOM operation dynamically added script, including loading external files and add internal code block two, dynamic loading of external files can run immediately, and dynamically added code block can not be executed immediately; A small exploration of dynamic script loading, execution and jquery practices, angularjs related practices;

1. Dynamic loading of external files

Because the dynamic loading of external JS will be executed immediately, there is no browser compatibility problem, this good processing; the point here is how to know that the script has been loaded to complete it? Oh, then browser compatibility problems come! bsie!

1 //dynamically loading external JS files2 //Params:url,loaded,error3 varasyncscripts=function() {4     functionload () {5         varargs=arguments;6         varHead = document.getElementsByTagName (' head ') [0]; 7         varJS = document.createelement (' script '); 8Js.type= ' Text/javascript '; 9Js.src=args[0]; Ten Head.appendchild (JS);  One         if(document.all) { AJs.onreadystatechange =function () {      -                 if(Js.readystate = = ' Loaded ' | | js.readystate = = ' complete ') { -Args[1]&&args[1](); the                 }                -             }           -}Else {                  -Js.onload =function () { +Args[1]&&args[1](); -             }            +         } AJs.onerror=function(){ atArgs[2]&&args[2](); -         } -     } -     functionExecjsblock () { -  -     } in     return { - Load:load, to Exec:execjsblock +     } - }(); the  *Asyncscripts.load (' Http://cdn.famanoder.com/lib/jquery0.js ',function() { $ alert ($)Panax Notoginseng});

2. Execute the dynamically loaded code block immediately

Theoretically speaking, Script.appendchild (createTextNode (CODESTR)), able to run normally, has to continue bsie here, because,<script> in IE is considered a special element (<style > similar), does not allow the DOM to access its child nodes, however, you can use the Text property of <script> to specify the code block to run properly;

1 //Params:scriptsstr2 varasyncscripts=function() {3     functionExecjsblock (scriptsstr) {4         varScript=document.createelement (' script ');5Script.type= ' Text/javascript ';6         if(document.all) {7script.text=Scriptsstr;8}Else {9 Script.appendchild (document.createTextNode (SCRIPTSSTR));Ten         } One document.body.appendChild (script); A     } -     return { - Exec:execjsblock the     } - }(); -Asyncscripts.exec (' var a=1000;alert (document.body.clientwidth+ "; +a) '); - //in fact, the method is the same as eval (SCRIPTSSTR);

3. Dynamic load Style

Dynamic loading JS and dynamic loading style The two are basically the same way, there are basically the same problems; not the same as a script, a create Style/link , on IE is script.text, and the normal practice is Script.appendchild (document.createTextNode (SCRIPTSSTR)); In IE is style.stylesheet.cssText, the normal practice is Style.appendchild (document.createTextNode (STYLESSTR)), but also note that link only in the head of the effective, This cannot be like the Script/style tag can be in the body;

Dynamic loading JS, the callback of the successful error, the code block executes immediately, a little to tidy up, presumably this:

1 varasyncscripts=function() {2     functionload () {3         varargs=arguments;4         varHead = document.getElementsByTagName (' head ') [0]; 5         varJS = document.createelement (' script '); 6Js.type= ' Text/javascript '; 7Js.src=args[0]; 8 Head.appendchild (JS); 9         if(document.all) {TenJs.onreadystatechange =function () {      One                 if(Js.readystate = = ' Loaded ' | | js.readystate = = ' complete ') { AArgs[1]&&args[1](); -                 }                -             }           the}Else {                  -Js.onload =function () { -Args[1]&&args[1](); -             }            +         } -Js.onerror=function(){ +Args[2]&&args[2](); A         } at     } -     functionExecjsblock (scriptsstr) { -         varScript=document.createelement (' script '); -Script.type= ' Text/javascript '; -         if(document.all) { -script.text=Scriptsstr; in}Else { - Script.appendchild (document.createTextNode (SCRIPTSSTR)); to         } + document.body.appendChild (script); -     } the     return { * Load:load, $ Exec:execjsblockPanax Notoginseng     } -}();

4, jquery How to do

The script added in jQuery1.4.1 and before the dynamic DOM operation will not be executed, this issue has been fixed in 1.4.2 and later versions, kneel down to my great jquery! Keep bsie!. So the script and style in the code below will immediately see the effect:

1 $ (selector). Append (' <script>alert (1) </script> '); 2 3 $ (selector). HTML (' <script>alert (1) </script> '); 4 5 $ (selector). Append (' <style>.a{color:red;} </style> ');

5, Angularjs on the dynamic addition of HTML and instruction processing

In angular if ng-bind= ' HTML string ', angular will treat HTML string as text, unlike the jquery above will help you execute the script inside, even if ng-bind-html= ' HTML string ' , and not as you wish; Yes, angular is very powerful, this problem it early thought, $SCE service is to deal with this, $sce translation is "strict context mode", then you can first inject the $SCE service, then call Trustashtml (_html), Achieve the results we want through ng-bind-html;

1 [' $scope ', ' $sce ',function($scope, $sce) {2     $scope. trusthtml=  function(_html) {3         return  $sce. trustashtml (_html); 4     }; 5 }];

To make it easier to call elsewhere, we can encapsulate it as a filter:

1 function ($SCE) {    2     returnfunction  (_html) {3          return  $sce. trustashtml (_html); 4     }; 5 }]);

Just learned Angularjs also encountered a problem: Dynamically added instructions can not be run, because after the page load angular will start collecting instructions from Ng-app and then compile, so the dynamically added instructions are not in scope, then need to compile the instructions again, by the $ Compile service to do this in link;

1 Link:function($scope, $element, $attrs) {2    angular.element (domobj). HTML (_html); 3     $compile (angular.element (domobj). Contents ()) ($scope); 4 };

6. It's a crooked end.

Beginner Angularjs, is transforming the background of the blog program, hehe, continue to dig pits, slowly pits;

"Senior" is a good book, busy to see the total harvest;

Some people say that accustomed to jquery, to change a way of thinking to learn angular; some people say that writing angular best not to use jquery pointers, such as Dom operation, but also someone angular and jquery mixed together;

I feel that jquery and angular are the product of two completely different ways of thinking, because it's understandable to avoid manipulating the DOM, but I'm always feeling awkward; I want to be a project fit angular thinking to do, you should abandon the brain of a large number of DOM operations , try to angular the pointers to do, even if there is DOM operation, angular also have corresponding practices, then jquery can rest; see angular service with $ symbol, bring the earth heroic ah, students together refueling!!!

Dynamic JS, dynamic style of "senior" notes

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.