Passing Arguments To Embedded JavaScript

By Rich Jones

So, you're writing an embedded script and you want to pass some arbitrary arguments and parameters to your javascript. How do you do it? This quick little tutorial will show you two examples, one using the HTML5 data attribute, and the other using the query string.

Method 1: HTML5 'data' Attribute

This is the easiest method. HTML5 now supports arbitrary parameters as long as they are prefixed with 'data-', so you can pass any arguments to your function with that.

So, your embed will look like this:

    	<script id="searcher" data-search="bananas"  
        src="http://yoursite.io/searcher.js" >

Then, inside your javascript:

      var script_tag = document.getElementById('searcher')
      var search_term = script_tag.getAttribute("data-search");

And that's it! Easy peasy.

The downside of this is that some very very old browsers might not like your arbitrary HTML5 attributes. In that case, you can use the querystring approach.

Method 2: Use the QueryString

In this case, you're just going to pass your parameters to the javascript as part of the query string, just like on any other GET request.

So, your embedded script tag will look like this: So, your embed will look like this:

     <script id="searcher" 
    src="http://yoursite.io/searcher.js?search=bananas">

Then, your JavaScript will look like this:

var script_tag = document.getElementById('searcher');
var query = script_tag.src.replace(/^[^\?]+\??/,''); 
 // Parse the querystring into arguments and parameters
 var vars = query.split("&");
 var args = {};
 for (var i=0; i<vars.length; i++) {
     var pair = vars[i].split("=");
     // decodeURI doesn't expand "+" to a space.
     args[pair[0]] = decodeURI(pair[1]).replace(/\+/g, ' ');   
 }
var search_term = args['search'];

And that's it! It's slightly uglier than the previous method, but it'll work on older browsers. Probably.

And that's it! Did this work for you?

 

Best Sites to Find Clients as a Freelance Developer

Fill your pipeline with best-fit clients for your rate, engagement length, and role preferences.

Take The Quiz

 

 

See More Posts About:

JavaScript


Posted by Rich Jones

LinkedIn Website