本文介绍了根据需求加载JavaScript依赖关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我确信这个问题有不同的方法,我可以想一些。但我想听听其他人对此的看法。更具体地说,我已经构建了一个小部件,允许用户从谷歌地图地图中选择他们的位置。这个小部件按需显示,并且可能每10分之一用于它所在的页面。加载这个小部件(谷歌地图js api)的依赖关系的最简单方法是在页面中放置一个脚本标签。但是这会使浏览器请求每个页面上的脚本加载。我正在寻找一种方法来让浏览器只在用户要求显示小部件时才请求脚本。

p $ p> 函数loadJSInclude(scriptPath,callback)
{
var scriptNode = document.createElement('SCRIPT');
scriptNode.type ='text / javascript';
scriptNode.src = scriptPath;

var headNode = document.getElementsByTagName('HEAD');
if(headNode [0]!= null)
headNode [0] .appendChild(scriptNode);

if(callback!= null)
{
scriptNode.onreadystagechange = callback;
scriptNode.onload = callback;




$ b $ p
$ b

使用(我以swfObject为例) :

  var callbackMethod = function()
{
//加载swfObject $ b后执行的代码

$ b //包含SWFObject(如果需要)
if(typeof(SWFObject)=='undefined')
loadJSInclude('/ js / swfObject.js',callbackMethod );
else
callbackMethod();


I'm sure there are different approaches to this problem, and I can think of some. But I'd like to hear other people's opinion on this. To be more specific I've built a widget that allows users to choose their location from a google maps map. This widget is displayed on demand and will probably be used every 1 out of 10 uses of the page where it's placed. The simplest way to load the dependency for this widget (google maps js api) is to place a script tag in the page. But this would make the browser request that script on every page load. I'm looking for a way to make the browser request that script only when the user requires for the widget to be displayed.

解决方案
function loadJSInclude(scriptPath, callback)
{
    var scriptNode = document.createElement('SCRIPT');
    scriptNode.type = 'text/javascript';
    scriptNode.src = scriptPath;

    var headNode = document.getElementsByTagName('HEAD');
    if (headNode[0] != null)
        headNode[0].appendChild(scriptNode);

    if (callback != null)    
    {
        scriptNode.onreadystagechange = callback;            
        scriptNode.onload = callback;
    }
}

And to use (I used swfObject as an example):

var callbackMethod = function ()
{
    // Code to do after loading swfObject
}

// Include SWFObject if its needed
if (typeof(SWFObject) == 'undefined')    
    loadJSInclude('/js/swfObject.js', callbackMethod);
else
    callbackMethod();

这篇关于根据需求加载JavaScript依赖关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 05:29