For web programmers, dealing with simple URL formats may be a nightmare. Just imagine that there are many components in a URL that will affect your analysis of it:
・・・Does it start with / character
・・・Does it start with //
・・・Does it start with a ?
・・・Does it start with #
…etc
When you want the absolute address of this address, how to judge the processing and parsing? It may be from http protocol or from https protocol. It's a headache. Fortunately, we have an easy way to determine its absolute address, which is to create an A element to assist in completing this task!
JavaScript Code
Here I will use a JavaScript function that returns the function. There are many benefits to doing this, which will be discussed below.
var getAbsoluteUrl = (function() { var a; return function(url) { if(!a) a = document.createElement('a'); a.href = url; return a.href; };})();This function looks a bit complicated. It first assigns a function to a variable, and there is another function in this function and a predefined variable. Someone may ask why a function needs to be embedded, and whether it can be simplified to this:
var getAbsoluteUrl = function(url) { var a = document.createElement('a'); a.href=url; return a.href;}Of course, this simple writing method cannot be miscalculated, but it is not perfect enough, because although the practice of embedding a function increases the complexity of the code, it can ensure that the A element is created only once and can be reused, saving time and memory.
Maybe someone will ask another question, wondering if there is a if judgment in the nested second function, why it is needed, and why not write it as follows:
var getAbsoluteUrl = (function() { var a = document.createElement('a'); return function(url) { a.href = url; return a.href; };})();This is naturally a way to run, and there will be no errors in the function. But the subtle thing is that if there is no if judgment statement, when defining this function, even if the function is not called by any code, the A element will be initialized. With the if judgment statement, the A element will be created when it is actually used, and there will be no waste of memory and CPU.
OK, with this method, no matter what kind of URL address you pass it in, it will return the absolute address.
Everyone, let’s try it!
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.