Causes and Solution of failures head into js

Original link: https: //www.jb51.net/article/107727.htm

 

1. invalid reasons:

Because the document has not been loaded, he attended the js, js no effect on

2. extension:

1 transmission and rendering pages js block the page in the head ". js need to be performed within the head end began to render body, so try not to js files placed in the Head. Future avoid head introduced js script blocking browser main parsing engine parses the work of the dom, rendering dom, the general principle is the style in front, dom document, script in the final surface, follow the first resolved in rendering the execution script this order .

2 "js divided into external and internal, external, generally into the head, generally placed inside the body, there are many such purposes:

  a. not to block the page is loaded (in fact are cached)

  b. can be operated in js dom, the dom is ready at this time, which is to ensure js runtime dom is there

  c. The recommended way is on the bottom of the page, or listening readystate window.onload to trigger js.

3 "namespace

Global variables can be bound to windowa different JavaScript files If you use the same global variable, or define a top-level function of the same name, will cause naming conflicts, and difficult to find.

One way to reduce conflict is all your own variables and functions all bound by a global variable. E.g:

// 唯一的全局变量MYAPP:
var MYAPP = {};

// 其他变量:
MYAPP.name = 'myapp';
MYAPP.version = 1.0; // 其他函数: MYAPP.foo = function () { return 'foo'; }; 

All the code into their own unique name space MYAPP, the variable will greatly reduce the possibility of global conflict.

3. Solution

   a. js into the body, preferably on the bottom

    b. () {} with the code wrapping by the document introduction window.onload = function or directly on the head of the

Guess you like

Origin www.cnblogs.com/Spring-Rain/p/11964121.html