Prevent jQuery multiple reference

狂风中的少年 提交于 2019-11-30 18:37:55

问题


I am developing DNN modules and I am using jQuery in some modules, I add the jQuery reference to the top of each ascx file, by the way when user add multiple modules to the page it references every time when modules are added, this situation gives some errors, when I remove the reference from the module which is bottom of the other module which both use jQuery, they work well, is there a way to prevent multiple reference the jQuery ? I mean if it is referenced on the page before it won't reference again. Thanks.


回答1:


You could make small script to check if jQuery is present on the page, and only if is not present, load it:

// 'load-jquery.js'
window.onload = function () {
  if (window.jQuery === undefined) {
    var script = document.createElement('script');
    script.src = 'path/to/jquery.min.js';
    document.getElementsByTagName('head')[0].appendChild(script); // load jQuery
  }
};



回答2:


If you're on DNN 5.x, you should be using the DNN core's version of jQuery, by calling DotNetNuke.Framework.jQuery.RequestRegistration().

If you're only dealing with conflict within your own modules, you can add the script in code and then check if it's already been added. We add jQuery manually into the header (create a generic HTML control, and add it to Page.Header.Controls), then call Page.ClientScript.RegisterClientScriptBlock() to create a script block to call jQuery.noConflict (so that it doesn't interfere with DNN's JavaScript stuff). You can then wrap the whole call to add jQuery in a call to Page.ClientScript.IsClientScriptBlockRegistered(), so that it only gets added once.




回答3:


If you're loading jQuery in a high-conflict environment, try namespacing jQuery.

SOMETHING = {
    jQuery: jQuery,
    $: $
}

And then call jQuery via SOMETHING.$ or SOMETHING.jQuery. Just remember to do the namespacing as soon as the version of jQuery you want has loaded, or else you'll end up with the wrong one. If you have access to the jQuery file, the easiest way to do this is to append the namespacing code at the end of the file.



来源:https://stackoverflow.com/questions/1356279/prevent-jquery-multiple-reference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!