开发者

Javascript include control depending on page

开发者 https://www.devze.com 2023-03-22 14:44 出处:网络
I\'m working as a client-side developer on a web app and found myself having lots of mo开发者_运维问答dules, each one for different pages. I wonder is it a good idea to do include depending on route m

I'm working as a client-side developer on a web app and found myself having lots of mo开发者_运维问答dules, each one for different pages. I wonder is it a good idea to do include depending on route myself (in javascript) or pass this responsibility to back-end (ruby on rails) guys.

I suppose I need some application.js to be included in every page, and in it do something like this:

if (window.location.href == '.../somePage') {
    loadScript('somePageControls.js')
}

if (window.location.href == '.../anotherPage') {
    ...
}

Any thoughts?


ok, this is not a simple answer at all, since there are you and there are theese ruby-guys, hope everything is ok beetwen you! ;)

although if you don't want to bother too much theese guys, ( i know it not easy to work in team ) you can ask to include just one ruby file from your working folder ex.

/web-app/ruby-guys/you/ruby-js.rb

now you can work with this unique file and load from here all the js file you need. by using for eaxmple a switch-case

case url-query
  when x
    # print out drag-drop.js
  when y, z
    # print out mouse-move.js 


You should pass that on to the server-side guys. It's a lot cleaner to output that sort script inclusion server side, since they can just add it to the pages you need it on rather than having a big if-else.


$0.02 from me ... If you'd like to minimize round trips to a (Rails) server, you could simply use a hash tag at the end of your urls, and parse the hash tag to determine which modules were necessary. This would allow you to put your page on a CDN if necessary, and enable you to dynamically change which modules were loaded on a page just by having a server redirect to the same page with a different hash tag.

E.g.

// Example URL: http://example.com/index.html#mod1,mod2,mod3,mod4
var loadModules = function() {
    var modsArr, i, len;
    if (!location.hash) return false;

    modsArr = location.hash.substr(1).split(','); // ["mod1", "mod2", "mod3", "mod4"]
    if (!modsArr.length) return false;

    for (i=0, len = modsArr.length; i < len; i++) {
        // Now you can load your mods.
    }

}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号