Home » JavaScript » The 7 delay loading JavaScript method (RPM)

The 7 delay loading JavaScript method (RPM)

delayed loading JavaScript, that is, after the completion of the page load, loading JavaScript, also known as on demand (on-demand) loading, there are generally a few ways:


1. DOM


head append script tag


window.onload = function () {
SetTimeout (function () {
To / / reference
Var head = document.getElementsByTagName (' head') [0];
New CSS / / A
Var CSS = document.createElement (' link');
Css.type = "text/css"";
Css.rel = "stylesheet"";
Css.href = "new.css"";
New JS / / A
Var JS = document.createElement ("script");
Js.type = "text/javascript"";
Js.src = "new.js"";
JS and CSS / / preload
Head.appendChild (CSS);
Head.appendChild (JS);
Preload / / image
New Image ().Src = "new.png"";
}, 1000);
};
2. document.write


3. Iframe



is similar to the first, but script tag is placed in the iframe of document,.


window.onload = function () {
SetTimeout (function () {
New iframe / / create
Var iframe = document.createElement (' iframe');
Iframe.setAttribute ("width", "0");
Iframe.setAttribute ("height", "0");
Iframe.setAttribute ("frameBorder", "0");
Iframe.setAttribute ("name", "preload");
Iframe.id = "preload"";
Iframe.src = "about:blank"";
Document.body.appendChild (iframe);
Gymnastics to get reference to the / iframe document
Iframe = document.all? Document.all.preload.contentWindow: window.frames.preload;
Var doc = iframe.document;
Doc.open (); doc.writeln (""); doc.close ();
Create / / CSS
Var CSS = doc.createElement (' link');
Css.type = "text/css"";
Css.rel = "stylesheet"";
Css.href = "new.css"";
Create / / JS
Var JS = doc.createElement ("script");
Js.type = "text/javascript"";
Js.src = "new.js"";
CSS and JS / / preload
Doc.body.appendChild (CSS);
Doc.body.appendChild (JS);
Preload / / IMG
New Image ().Src = "new.png"";
}, 1000);
};


4. Iframe static page


directly loads what needs to be put into another page,


window.onload = function () {
SetTimeout (function () {
Create a new frame and point / to the URL of the static
Page that has all components to / / preload
Var iframe = document.createElement (' iframe');
Iframe.setAttribute ("width", "0");
Iframe.setAttribute ("height", "0");
Iframe.setAttribute ("frameBorder", "0");
Iframe.src = "preloader.html"";
Document.body.appendChild (iframe);
}, 1000);
};


5. Ajax eval


downloads the code with Ajax, and then executes the

with Eval


6. AjaxInjection


downloads the code with Ajax, builds an empty script tag, and sets the text attribute for the downloaded code



The

7. async attribute (the disadvantage is that the order of loading cannot be controlled)