A method to pass configuration parameters through script custom properties

  • 2020-03-30 03:55:01
  • OfStack

Just started a formal career, in the last few days to do a unified head js for the company, came up with a way to pass configuration parameters through script custom properties.

Sometimes we write a js plug-in, and to use the plug-in, we need to introduce the plug-in js into the HTML, and then add a script tag, which is called inside. Such as a picture switch plug-in. The code is roughly as follows:


$.fn.picSwitch = function(option){
//Here is the code for image switching
}

After the plug-in is introduced, you need to add the calling code in another script tag


$('#pic').picSwitch({
'speed' : '400',
'derection' : 'left'
//. So here's the configuration
})

That's fine, but sometimes we don't want to add more script tags, so if we just introduce script tags, how do we do that and how do we pass configuration parameters?

At this point we can use the custom properties on the script to pass the configuration parameters. Before you do this, you need to process the image switch plug-in. The modified code is as follows:


$.fn.picSwitch = function(){
//Here is the code for image switching
};

// write the plug-in and call it directly
$(' here is the selector, need to get on the script TAB '). PicSwitch (' here is the configuration parameter, need to get on the script TAB ');

The next step is to pass the parameters on the script and refer to the js plug-in on the HTML page as follows.


<head>
<script src='/script/picSwitch.js' id='picSwitch' obj='#pic' option='{"speed":"400","derection":"left"}'></script>
</head>
<body>
<div id="pic">
//Here is the concrete structure
</div>
</body>

The last plugin to be modified is:


$.fn.picSwitch = function(){
//Here is the code for image switching

};

//Call it directly after writing the plug-in
var script = $('#picSwitch') . //The id on the label
selector = script.attr('selector'),
option = JSON.parse(script.attr('option'));//The string on the tag needs to be converted to a json object
$(selector).picSwitch(option);

In this way, only one tag is used to achieve the function, and the configuration changes only need to change the script custom properties.


Related articles: