JavaScript CDN introduction failure solution

Sometimes we introduce jquery through cdn, but it will inevitably make mistakes, what should I do? We can use cdn and local import together to make a judgment. When the cdn import is successful, we will not import the local jquery. If the CDN import fails, then we will import the local jquery.

You only need to import the corresponding jquery into the address to modify it. The rest does not need to be modified.

Not much to say, look at the code:

the first method

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		
		<!-- CDN引入 -->
		<script src="https://www.jq22.com/jquery/jquery-3.3.1.j"></script>
	</head>
	<body>
		
	</body>
	<!-- 当CDN引入失败的时候指向这段代码 -->
	<script type="text/javascript">
	 if (typeof jQuery == 'undefined') {
     
     
	 document.write(unescape("%3Cscript src='../js/jQuery_js.js' type='text/javascript'%3E%3C/script%3E"));
	 }
	</script>
	
</html>

We directly use URL encoding in the document.write method, encoding "<" as "%3C", and then we use the unescape() method to restore the string.

We convert the string back through the unescape() method, and we can see that the output is a normal script quote code.

Now, we have a question: "Why not use regular characters, but use character encoding?" In fact, there is a reason for this, which means that our code will be able to run normally in XML, XHTML or HTML, without the need Include the code in the CDATA (label).

The second method

<!-- CDN引入 -->
<script src="https://www.jq22.com/jquery/jquery-3.3.1.j"></script>
		<!-- 本地引入 -->
<script>window.jQuery || document.write(unescape("%3Cscript src='../js/jQuery_js.js' type='text/javascript'%3E%3C/script%3E"))</script>

The above is the same as the first principle, that is, through the || operator, if window.jQuery is false, the local jquery library is loaded.

Guess you like

Origin blog.csdn.net/m0_46188681/article/details/108897638