Lazy loading of javascript, that is, loading javascript after the page is loaded, also called on demand (on demand) loading. There are generally several methods:
1. DOM
head append script tag
= function() { setTimeout(function(){ // reference to <head> var head = ('head')[0]; // a new CSS var css = ('link'); = "text/css"; = "stylesheet"; = ""; // a new JS var js = ("script"); = "text/javascript"; = ""; // preload JS and CSS (css); (js); // preload image new Image().src = ""; }, 1000); };
2.
<script language="javascript" type="text/javascript"> function include(script_filename) { ('<' + 'script'); (' language="javascript"'); (' type="text/javascript"'); (' src="' + script_filename + '">'); ('</' + 'script' + '>'); } var which_script = ''; include(which_script); </script>
3. Iframe
Similar to the first type, but script tag is placed in the iframe document.
= function() { setTimeout(function(){ // create new iframe var iframe = ('iframe'); ("width", "0"); ("height", "0"); ("frameborder", "0"); ("name", "preload"); = "preload"; = "about:blank"; (iframe); // gymnastics to get reference to the iframe document iframe = ? : ; var doc = ; (); ("<html><body></body></html>"); (); // create CSS var css = ('link'); = "text/css"; = "stylesheet"; = ""; // create JS var js = ("script"); = "text/javascript"; = ""; // preload CSS and JS (css); (js); // preload IMG new Image().src = ""; }, 1000); };
4. Iframe static page
Put the things you need to load directly into another page
= function() { setTimeout(function(){ // create a new frame and point to the URL of the static // page that has all components to preload var iframe = ('iframe'); ("width", "0"); ("height", "0"); ("frameborder", "0"); = ""; (iframe); }, 1000); };
5. Ajax eval
Download the code with ajax and then execute with eval
6. Ajax Injection
Use ajax to download the code, create an empty script tag, and set the text attribute to the downloaded code
7. async attribute (the disadvantage is that it cannot control the order of loading)
<script src="" async="true"/>
This is the end of this article about the implementation of 7 methods of lazy loading in javascript. For more related javascript lazy loading content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!