Based on a partial summary of recent problems, solutions to future problems will be added

Dynamically add CSS files

Application Scenarios:

  • Change skin function
  • A set of code used in different areas, different areas of different styles
  • A set of code for different user use, user personalized Settings function

So how do you dynamically add different CSS files?

 /** * @param {String} cssName: CSS name without suffix * @param {String} prefix: CSS prefix */
function dynamicAddCss(cssName,prefix=""){
    let link = document.createElement('link')
    link.setAttribute('href',prefix+cssName+'.css')
    link.setAttribute('type'.'text/css')
    document.getElementsByTagName('head') [0].appendChild(link)
}
dynamicAddCss('a'.'http://www.baidu.com/app/a/')
dynamicAddCss('b'.'http://www.baidu.com/app/b/')
Copy the code

Add JS files dynamically

Sometimes, in our front-end development, some data files are stored in our server, and we need to get this data and do some operations, such as banner configuration data, or some other data.

Banner.js stored on the server

const Config = {
    banner:[
        {img:'www.baidu.com/1.png'.id:"1"},
        {img:'www.baidu.com/2.png'.id:"2"},
        {img:'www.baidu.com/3.png'.id:"3"},
        {img:'www.baidu.com/4.png'.id:"4"]}},Copy the code

Json.js stored on the server

var list = [1.2.3.4.5]
Copy the code

Methods:

 /** * @param {Array} scriptUrlArr: an Array of scripts * @param {Function} callback: a callback */
function dynamicAddScript(scriptUrlArr,callback){
    scriptUrlArr.forEach(scriptUrl= >{
        let script = document.createElement('script')
        script.setAttribute('src',scriptUrl)
        document.body.appendChild(script) 
    })
    window.onload = function(){
        callback && callback()
    }
}
Copy the code

Use:

 dynamicAddScript(['http://moxiaofei.com/banner.js'.'http://moxiaofei.com/json.js'], () = > {console.log(Config)  //{banner: Array(3)}
    console.log(list)    //[1, 2, 3, 4, 5]
})
Copy the code

Data file variables that exist on the server are recommended to be declared as let or const. Var overwrites the same variables in the previous script

LocalStorage to monitor

  • Localstorage. setItem Listens for: custom event setItemEvent
  • Localstorage. getItem Listens to: custom event getItemEvent
  • Localstorage. removeItem Listens for: custom event removeItemEvent
// Listen for custom event setItemEvent
localStorage.setItem = (Orgin= >{
    return function(key,value){
        let setItemEvent = new CustomEvent('setItemEvent', {detail: {setKey:key,value}})
        window.dispatchEvent(setItemEvent)
        Orgin.call(this,key,typeof value == 'string'? value : JSON.stringify(value))
    }
})(localStorage.setItem)

// Listen for the custom getItemEvent
localStorage.getItem = (Orgin= >{
    return function(key){
        let result = JSON.parse(Orgin.call(this,key))
        let getItemEvent = new CustomEvent('getItemEvent', {detail: {getKey:key,value:result}})
        window.dispatchEvent(getItemEvent)
        return result 
    }
})(localStorage.getItem)


// Listen for the custom event removeItemEvent
localStorage.removeItem = (Orgin= >{
    return function(key){
        let removeItemEvent = new CustomEvent('removeItemEvent', {detail: {removeKey:key}})
        window.dispatchEvent(removeItemEvent)
        Orgin.call(this,key)
    }
})(localStorage.removeItem)
Copy the code

Listening:

/ / localStorage. SetItem listening in
window.addEventListener('setItemEvent'.function(e){
    console.log(e.detail)
})

/ / localStorage. The getItem to monitor
window.addEventListener('getItemEvent'.function(e){
    console.log(e.detail)
}) 

/ / localStorage. RemoveItem listening in
window.addEventListener('removeItemEvent'.function(e){
    console.log(e.detail)
})
Copy the code

Actively trigger methods that exist in the DOM

function trigger(Node,EventType) {
    if(EventType in Node)Node[EventType]()
}
Copy the code

Actively trigger custom methods

let oDiv = document.querySelector('#div')

oDiv.addEventListener('DefineMethod'.function(){
    alert('Custom method is working')})function fireEvent(node,type) {
    var event = document.createEvent('Event');
    event.initEvent(type, true.true);
    node.dispatchEvent(event)
}

fireEvent(oDiv,'DefineMethod')
Copy the code

Overriding array methods

Overrides part of the array prototype method

const oldArrayProto = Array.prototype
const newArrayProto = Object.create(oldArrayProto)
const rewriteMethod = ['push'.'splice']
const instenceArr = []
instenceArr.__proto__ = newArrayProto
rewriteMethod.forEach(method= >{
    let orgin = newArrayProto[method]
    newArrayProto[method] = function(){
        orgin.apply(this.arguments) notify(method,... arguments) } })function notify () {
    let [method,...rest] = [...arguments]
    console.log(method)
    console.log(rest)
}
Copy the code

The example overrides the two methods of the array, push and splice, and adds notify to the override method that listens when you push or splice the array instenceArr

Rewrite the console log

Requirement: If the first argument is an object, the output string JSON does not affect other functions

console.log = (orgin= >{
    return function(){
        // If the object is a string JSON
        arguments[0] =  typeof arguments[0] = ='string'?arguments[0] :JSON.stringify(arguments[0])
        orgin.call(console. arguments) } })(console.log)
Copy the code

Only execute the function once

2020/4/14 update

Function rewrite is null

function RunOnce(fn){
    fn()
    RunOnce = function(){} 
}

RunOnce(function(){
    console.log(111)
})
RunOnce(function(){/ / does not perform
    console.log(111)})Copy the code

Function object properties mount

function RunOnce(fn){
    if(! RunOnce[fn]){ fn() RunOnce[fn] =true}}let a1 = function(){
    console.log(11)}let b1 = function(){
    console.log(22)
}
RunOnce(a1)/ / 11
RunOnce(a1)/ / does not perform
RunOnce(b1)/ / 22
RunOnce(b1)/ / does not perform
Copy the code

Tip: This approach is not suitable for anonymous functions

Continuously updated…

conclusion

If you have a better idea, or don’t find the tool function you want, feel free to leave a comment

Please point out any inaccuracies or errors in the article

Previous articles: Front-end code optimization utility