Home > Web Front-end > JS Tutorial > An include function implemented with JS_javascript skills

An include function implemented with JS_javascript skills

WBOY
Release: 2016-05-16 19:11:23
Original
1316 people have browsed it

Many languages ​​​​have functions similar to the include and require functions in php, but only javascript does not.
I have wanted to implement similar functions in js for a long time. I have tried many times without success. When I searched for some keywords about dynamically loading css files on Google that day, I found a blog (the address cannot be found). A function that adds a link element to the head tag of a web page, so I changed it and wrote this function.

Usage:
include_js(src,[reload]);
src: the path name of the js file
reload: optional parameter, 0 or 1, indicating whether to load the same url repeatedly js file.

Note:
When there is a document.write method in the included js file, there will be no response under IE, but under Mozilla Firefox, your original webpage will disappear and only document.write will be displayed. Content: mad:
Hey, I naturally have a trick for this problem:
It is to redefine the document.write method so that it does not display anything. Specific method:
Add this sentence before include_js
document.write = function () { return false;}
In this way, even if the included js file contains the document.write method, we are not afraid of it damaging the web page Got it! :lol::lol:

Purpose:
This function can be used to asynchronously load some advertising and statistical js files, avoiding the problem of slow web page display speed caused by loading js files.

Modify this function to dynamically load css files, but it is not as useful as loading js files.

Copy code The code is as follows:

function include_js(path,reload)
{
var scripts = document.getElementsByTagName("script");
if (!reload)
for (var i=0;i if (scripts[ i].src && scripts[i].src.toLowerCase() == path.toLowerCase() ) return;
var sobj = document.createElement('script');
sobj.type = "text/ javascript";
sobj.src = path;
var headobj = document.getElementsByTagName('head')[0];
headobj.appendChild(sobj);
}
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template