Question

I've created the function below, which will run on every page of my site. It runs fast enough but as it runs on every page, it seems to be a good candidate for being cached, maybe using memoization. In my research on the subject, memoization always caches the results that are being sent out with a return statement. This makes perfect sense but as my function isn't returning anything, I'm wondering if it can still be cached? Using something other than memoization perhaps?

Here's my function:

// A requirejs module
define(function() {

 var loadMenu,
   cssdisabled,
   testcss,
   currstyle; 

 /*  
  *  Dynamically create a form that looks like this:
  *
  *  <form action="/search.html" id="js-searchbox" class="form">
  *    <input type="text" name="q" id="tipue_search_input"
  *     placeholder="Search...">
  *    <input type="submit" id="tipue_search_button" value="Search">
  *  </form>
  */
 loadMenu = function() {
   var loadBox = document.getElementById("searchbox"),
     footerBox = document.getElementById("search-about-column"),
     frag = document.createDocumentFragment(),
     form = document.createElement("form"),
     searchTextBox = document.createElement("input"),
     searchButton = document.createElement("input");

 // set attributes for form
 form.action = "/search.html";
 form.setAttribute("role", "search");
 form.id = "js-searchbox";
 form.setAttribute("class", "form");

 // set attributes for Search text box
 searchTextBox.type = "text";
 searchTextBox.name = "q";
 searchTextBox.id = "tipue_search_input";
 searchTextBox.placeholder = "Search...";

 // set attributes for Submit button
 searchButton.type = "submit";
 searchButton.setAttribute("class", "btnSearch");
 searchButton.value = "Search";

 // Arrange elements
 form.appendChild(searchTextBox);
 form.appendChild(searchButton);

 // Load arranged elements into document fragment
 frag.appendChild(form);

 // Load document fragment into #searchbox, which is already on the page
 loadBox.appendChild(frag);
}

 cssdisabled = false;

 testcss = document.createElement('div');

 testcss.style.position = 'absolute';

 document.getElementsByTagName('body')[0].appendChild(testcss);

 if (testcss.currentStyle) {
   currstyle = testcss.currentStyle['position'];
 }

 else if (window.getComputedStyle) {
  currstyle = document.defaultView.getComputedStyle(testcss, null).getPropertyValue('position');
} 

 cssdisabled = (currstyle === 'static') ? true : false;

 document.getElementsByTagName('body')[0].removeChild(testcss);

 if (cssdisabled === false) {
   loadMenu();
 } else {
   return false;
  }

 });
Was it helpful?

Solution

Use the frag as your memo:

frag.appendChild(form);
loadMenu.frag = frag;

then update the assignment:

loadMenu = loadMenu.frag || function() {...}

References

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top