Multiple Threads and single threads of javascript;
In javascript, user-defined functions are run in a single thread, but after the rendering part is handed over to the browser, it is run in multiple threads. Other sequences are uncontrollable.
For example:
- Include = function (jsurl ){
- If (jsurl = null | typeof (jsurl )! = 'String') return;
- Var js = document. createElement ('script ');
- Js. type = 'text/javascript ';
- Js. charset = 'utf-8 ';
- Js. src = jsurl;
- Var heads = document. getElementsByTagName ('head ');
- Heads [0]. appendChild (js );
- // Implement 2
- Document. write ('<script type = "text/javascript" src = "' + jsurl + '"> </script> ');
- Console.info ("include" + jsurl + "finished ");
- }
The code is completed in two ways: Insert a script node, and dynamically write a node through the document;
If the first implementation is used at this time, when multiple js files are added, the head will be inserted at the same time. The loading of these files is controlled by multiple threads in the browser; the loading order cannot be guaranteed, {for example, first include (". js "), in include (" B. js "), B uses the object defined by}
It is not loaded first if it is included first (a cannot be guaranteed to be loaded first ). therefore, if the file to be loaded is dependent at this time, the variable is undefined. It is found through testing. even if it is loaded first, there will be undefined conditions in the future. It is estimated that this is caused by multi‑thread synchronization;
For the second method, you can ensure that the generated script header is consistent with the effect of directly writing the script in html, and the loading sequence is ensured;
Taking this as an example, we can guess that other paintors have the same effect. That is, not necessarily the first append element. Of course, this time difference is very small, and the eyes on the interface cannot find it at all;