This time I will show you how to load jquery.js in a JS file (with code), and what are the precautions for loading jquery.js in a JS file. The following is a practical case, let’s take a look. take a look.
There is a requirement recently: 1. Only one JS file can be introduced into an html, and no JS code or other JS files can be introduced; 2. This JS Other JS files must be introduced into the file; 3. All JS functions are written in this JS file. These codes use jquery-related stuff, so the first thing that needs to be solved here is how to introduce jquery. js. Searchedon the Internet and many methods were not very practical. Since I have been away from the WEB for many years, I finally asked a friend and got the following code:
1.js// by firefoxmmx
var script=document.createElement("script");
script.type="text/javascript";
script.src="jquery.js";
document.getElementsByTagName('head')[0].appendChild(script);
setTimeout(function(){
$(document).ready(function(){
$("#bt").click(function(){
alert('Hello World');
});
});
},100);
<html>
<head>
<script type="text/javascript" src="1.js"></script>
</head>
<body>
<input type="button" id="bt" value="Click" />
</body>
</html>
After clicking the button, the effect is as shown below:
Here are some methods from the Internet:
1. Direct document.write
<script language="javascript"> document.write("<script src='test.js'><\/script>"); </script>
2. Dynamically change the src attribute of an existing script
<script src='' id="s1"></script> <script language="javascript"> s1.src="test.js" </script>
3. Dynamically create a script element
<script> var oHead = document.getElementsByTagName('HEAD').item(0); var oScript= document.createElement("script"); oScript.type = "text/javascript"; oScript.src="test.js"; oHead.appendChild( oScript); </script>
I believe you have mastered the method after reading the case in this article, and there will be more exciting things. Please pay attention to other related articles on php Chinese website!
Recommended reading:
Detailed explanation of usage examples of this pointer in JS
##node koa2 mysql bootstrap to build forum front-end and back-end
The above is the detailed content of How to load jquery.js in a JS file (code attached). For more information, please follow other related articles on the PHP Chinese website!