Best practices for managing JavaScript on a single page application

In a single page application, where I change the hash and load and change only the contents of the page, I am trying to decide how to control the JavaScript that may be needed for each page.

I already have a History module that tracks a location hash that might look like domain.com/#/company/about, and a page class that XHR will use to retrieve content and paste it into the content area.

function onHashChange(hash) {
    var skipCache = false;
    if(hash in noCacheList) {
        skipCache = true;
    } 
    new Page(hash, skipCache).insert();
}


// Page.js
var _pageCache = {};
function Page(url, skipCache) {

    if(!skipCache && (url in _pageCache)) {
        return _pageCache[url];
    }
    this.url = url;
    this.load();

}

The cache should allow pages that have already been loaded to skip XHR. I also save the content in documentFragment and then pull the current content from the document when I insert a new one Page, so I only need to create a DOM for the fragment.

, , .

:. , JavaScript . , , -, - , ajax --.

JavaScript ? script Fragment, XHR? , . , JavaScript, , , , .

Page? , , .

, , , JavaScript ?

+5
7

, , , , ajax, ?

, , script , ?

, , html dom:

//first set up a cache of urls you already have loaded.
var loadedScripts = [];

//after user has triggered the ajax call, and you've received the text-response
function clearLoadedScripts(response){
   var womb = document.createElement('div');
   womb.innerHTML = response;
   var scripts = womb.getElementsByTagName('script');
   var script, i = scripts.length;
   while (i--) {
      script = scripts[i];
      if (loadedScripts.indexOf(script.src) !== -1) {
          script.parentNode.removeChild(script);
      }
      else {
          loadedScripts.push(script.src);
      }
   }

   //then do whatever you want with the contents.. something like:
   document.body.innerHTML = womb.getElementsByTagName('body')[0].innerHTML);

}
+1

, , nbest, - (, HTTP-), script /, script .

0

? , IFrame.

HTML , , .

, HTML JS. , HTML- > JS . Pure JavaScript HTML Parser, JS-, , , DOM JQuery.

webapp, , , JS- HTML + JQuery, , , JPS Webapp .

0

, (.. ).

, :

  • , script . script XHR , .
  • (, DOM , ), . , , , script, init .
  • JS, /. : require_scripts('page_1_init', 'form_code', 'login_code') DOM script .
0

script, YUI Loader, LAB.js , jaf

Jaf ( HTML) js, css . . , , .

0

JSON HTML:

{
    "title": "About",
    "requires": ["navigation", "maps"],
    "content": "<div id=โ€ฆ"
}

, , . script, , , , , , ( <head>), .

Instead of including inline scripts for page-specific logic, I would use predefined classes, identifiers, and attributes for elements that need special handling. You can fire the onrender event, or let each piece of logic register the on-render callback that your page loader fires after the page is displayed or loaded for the first time.

0
source

All Articles